From 09db5e597982658e0d9c86883044df3747c0aff3 Mon Sep 17 00:00:00 2001 From: Andre Kurait Date: Thu, 26 Nov 2026 14:27:39 -0600 Subject: [PATCH] fix(route53): scope private DNS answers to the querying VPC (#9508) For an identified workload, Route 53 and Cloud Map private DNS answers come only from zones associated with the querying VPC, account and Region; visibility is decided before the most specific zone is chosen, authoritative negative answers are kept, and conflicting runtime identities are refused. A caller with no known VPC keeps its private answers. EC2 and ECS register their guests' VPCs for the lifetime of the workload, revoking them on confirmed stop, and a terminating instance's IAM sessions and metadata tokens are revoked independently of Docker removal. The guest DNS checks run as nightly Docker checks. --- .github/ci/prefetch-images.sh | 8 + .github/ci/select-nightly-checks.sh | 12 +- .github/ci/test_select_nightly_checks.py | 78 +++ .github/workflows/nightly-checks.yml | 1 + docs/services/cloudmap.md | 8 + docs/services/route53.md | 3 +- .../aws/core/common/dns/DnsRecordSource.java | 17 + .../core/common/dns/EmbeddedDnsServer.java | 48 +- .../docker/ContainerLifecycleManager.java | 25 + .../cloudmap/CloudMapDnsRecordSource.java | 14 +- .../services/cloudmap/CloudMapService.java | 18 +- .../aws/services/ec2/Ec2ContainerManager.java | 67 ++- .../aws/services/ec2/Ec2MetadataServer.java | 98 +++- .../io/floci/aws/services/ecs/EcsService.java | 23 +- .../ecs/container/EcsContainerManager.java | 149 +++++- .../route53/Route53DnsRecordSource.java | 59 ++- .../aws/services/route53/Route53Service.java | 90 ++-- .../dns/CloudMapDnsPacketIntegrationTest.java | 96 +++- .../aws/core/common/dns/DnsTestQuery.java | 23 + ...eDnsGuestDockerNightlyIntegrationTest.java | 194 ++++++++ ...eDnsGuestDockerNightlyIntegrationTest.java | 41 ++ ...eDnsGuestDockerNightlyIntegrationTest.java | 276 +++++++++++ ...eDnsGuestDockerNightlyIntegrationTest.java | 30 ++ ...eDnsGuestDockerNightlyIntegrationTest.java | 30 ++ .../common/dns/EmbeddedDnsServerTest.java | 27 ++ ...vateHostedZoneVpcScopeIntegrationTest.java | 283 +++++++++++ .../dns/Route53DnsPacketIntegrationTest.java | 138 +++++- ...ContainerLifecycleManagerTeardownTest.java | 45 ++ .../services/ec2/Ec2ContainerManagerTest.java | 23 +- .../aws/services/ec2/Ec2DnsLifetimeTest.java | 452 ++++++++++++++++++ ...Ec2InstanceCredentialsIntegrationTest.java | 18 +- .../services/ec2/Ec2MetadataServerTest.java | 57 +++ .../services/ec2/Ec2MetadataTokenTest.java | 14 + .../ecs/EcsServiceDaemonSchedulingTest.java | 52 ++ .../services/ecs/EcsServiceTeardownTest.java | 62 +++ ...ContainerManagerSharedTaskNetworkTest.java | 42 +- .../EcsContainerManagerTaskAddressTest.java | 346 +++++++++++++- ...ntainerManagerTaskRoleCredentialsTest.java | 16 +- .../EcsContainerManagerVolumesTest.java | 10 +- .../route53/Route53DnsResolutionTest.java | 151 ++++-- .../services/route53/Route53ServiceTest.java | 16 +- 41 files changed, 2919 insertions(+), 241 deletions(-) create mode 100644 src/test/java/io/floci/aws/core/common/dns/Ec2PrivateDnsGuestDockerNightlyIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/core/common/dns/Ec2ProtectedPrivateDnsGuestDockerNightlyIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/core/common/dns/EcsPrivateDnsGuestDockerNightlyIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/core/common/dns/EcsProtectedPrivateDnsGuestDockerNightlyIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/core/common/dns/EcsSharedPrivateDnsGuestDockerNightlyIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/core/common/dns/PrivateHostedZoneVpcScopeIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/ec2/Ec2DnsLifetimeTest.java diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh index be2e44daf9..d077039ad5 100755 --- a/.github/ci/prefetch-images.sh +++ b/.github/ci/prefetch-images.sh @@ -128,6 +128,14 @@ starts EcsImagePullDockerIntegrationTest && [ -n "$REGISTRY_IMAGE" ] && pull "$R PYTHON_ALPINE_IMAGE="$(test_image PYTHON_ALPINE)" starts ContainerCaBundleDockerIntegrationTest EcsCredentialsProxyDockerNightlyIntegrationTest SageMakerDockerNightlyIntegrationTest \ && [ -n "$PYTHON_ALPINE_IMAGE" ] && pull "$PYTHON_ALPINE_IMAGE" +# DNS lifecycle guests use Python, including inherited protected/shared checks. Their network helpers build +# from alpine:3.21 locally, so prefetch the base rather than pulling the locally built helper image. +if starts EcsPrivateDnsGuestDockerNightlyIntegrationTest EcsSharedPrivateDnsGuestDockerNightlyIntegrationTest \ + EcsProtectedPrivateDnsGuestDockerNightlyIntegrationTest Ec2PrivateDnsGuestDockerNightlyIntegrationTest \ + Ec2ProtectedPrivateDnsGuestDockerNightlyIntegrationTest; then + [ -n "$PYTHON_ALPINE_IMAGE" ] && pull "$PYTHON_ALPINE_IMAGE" + pull alpine:3.21 +fi CORRETTO_8_IMAGE="$(test_image CORRETTO_8)" starts ContainerCaBundleDockerIntegrationTest && [ -n "$CORRETTO_8_IMAGE" ] && pull "$CORRETTO_8_IMAGE" # The Firelens test names the log router image itself rather than taking it from config. diff --git a/.github/ci/select-nightly-checks.sh b/.github/ci/select-nightly-checks.sh index a751d35179..da5c53d22e 100755 --- a/.github/ci/select-nightly-checks.sh +++ b/.github/ci/select-nightly-checks.sh @@ -14,9 +14,10 @@ # - for each service whose src/main package (services//) it changes, the docker-e2e checks under # services// in src/test, the docker-e2e checks that import io.floci.aws.services., and the ones # CONSUMERS names for that service; +# - the DNS docker-e2e checks when it changes core/common/dns; # - every docker-e2e check when it changes core/common/docker, or changes an image pin: a changed line that mentions # "image" in application.yml (main or test) or under config/, or one of those files with no patch from GitHub; -# - for each other src/test/java class it changes, the docker-e2e checks that name that class. +# - for each src/test/java class it changes (including a nightly base class), the docker-e2e checks that name that class. # # Writes matrix= to $GITHUB_OUTPUT, or prints it when that is unset. Needs gh (for $PR) and jq. # SELECT_NIGHTLY_FILES, when set, names a JSON array of {filename, patch} read in place of the pull request's files @@ -30,6 +31,11 @@ TESTS=io/floci/aws IMAGE_PINS='^(src/(main|test)/resources/application\.yml|src/main/java/io/floci/aws/config/.*)$' # :, for checks that exercise a service without importing it. CONSUMERS=( + # Protected/shared DNS guests inherit service calls from their base test, so imports alone miss them. + 'ec2:/core/common/dns/(Ec2|Ecs).*PrivateDnsGuestDockerNightlyIntegrationTest$' + 'ecs:/core/common/dns/Ecs.*PrivateDnsGuestDockerNightlyIntegrationTest$' + 'route53:/core/common/dns/(Ec2|Ecs).*PrivateDnsGuestDockerNightlyIntegrationTest$' + 'cloudmap:/core/common/dns/(Ec2|Ecs).*PrivateDnsGuestDockerNightlyIntegrationTest$' # Redshift Spectrum and UNLOAD to Parquet run their SQL on floci-duck (services/floci/duck). 'floci:/services/redshift/(RedshiftSpectrum|RedshiftUnloadParquet)DockerNightlyIntegrationTest$' # These CUR checks write their report's Parquet through floci-duck under the report owner's account. @@ -74,6 +80,9 @@ if [ -n "${PR:-}" ]; then if grep -q "^$MAIN/core/common/docker/" "$work/changed.txt" || [ -n "$pins" ]; then cat "$work/e2e.txt" fi + if grep -q "^$MAIN/core/common/dns/" "$work/changed.txt"; then + grep '/core/common/dns/' "$work/e2e.txt" || true + fi sed -n "s|^$MAIN/services/\([^/]*\)/.*|\1|p" "$work/changed.txt" | LC_ALL=C sort -u | while read -r svc; do grep -E "^$TESTS/services/$svc/" "$work/e2e.txt" || true xargs grep -lE "^import (static )?io\.floci\.aws\.services\.$svc\." < "$work/e2e-sources.txt" \ @@ -86,7 +95,6 @@ if [ -n "${PR:-}" ]; then done # A src/test/java class's simple name; every test source is a top-level class, as ci.yml relies on. { grep -E '^src/test/java/.*\.java$' "$work/changed.txt" || true; } \ - | { grep -v 'NightlyIntegrationTest\.java$' || true; } \ | sed 's|.*/||; s|\.java$||' | LC_ALL=C sort -u | while read -r helper; do xargs grep -lw "$helper" < "$work/e2e-sources.txt" | sed 's|^src/test/java/||; s|\.java$||' || true done diff --git a/.github/ci/test_select_nightly_checks.py b/.github/ci/test_select_nightly_checks.py index cb63b4a65f..7ad36f5c9b 100644 --- a/.github/ci/test_select_nightly_checks.py +++ b/.github/ci/test_select_nightly_checks.py @@ -63,6 +63,11 @@ class SelectNightlyChecksTest(unittest.TestCase): def e2e(self, files): return self.select(files).get('docker-e2e', []) + def test_dnsChangesStartThePullRequestWorkflow(self): + workflow = PATH.parent.parent / 'workflows' / 'nightly-checks.yml' + pull_request = workflow.read_text().split(' pull_request:', 1)[1].split('\npermissions:', 1)[0] + self.assertIn(" - 'src/main/java/io/floci/aws/core/common/dns/**'", pull_request) + def test_scheduleRunsEveryCheck(self): groups = self.select() self.assertEqual(E2E, groups['docker-e2e']) @@ -140,5 +145,78 @@ class SelectNightlyChecksTest(unittest.TestCase): self.assertEqual({}, self.select({MAIN + '/services/sqs/SqsService.java': '+x'})) +ROOT = Path(__file__).resolve().parents[2] +TESTS = ROOT / 'src/test/java' +DNS = 'io/floci/aws/core/common/dns/' +NAMES = [kind + 'PrivateDnsGuestDockerNightlyIntegrationTest' for kind in + ('Ec2', 'Ec2Protected', 'Ecs', 'EcsProtected', 'EcsShared')] +EXPECTED = {DNS + name for name in NAMES} + + +class DnsGuestNightlyTest(unittest.TestCase): + def select(self, changed=None): + with tempfile.TemporaryDirectory() as directory: + env = dict(os.environ) + for key in ('PR', 'SELECT_NIGHTLY_FILES', 'GITHUB_OUTPUT'): + env.pop(key, None) + if changed is not None: + files = Path(directory) / 'files.json' + files.write_text(json.dumps([{'filename': path, 'patch': '+changed'} for path in changed])) + env.update(PR='1', SELECT_NIGHTLY_FILES=str(files)) + result = subprocess.run(['bash', '.github/ci/select-nightly-checks.sh'], cwd=ROOT, + env=env, capture_output=True, text=True, check=True) + return {name for group in json.loads(result.stdout) if group['group'] == 'docker-e2e' + for name in group['classes'].split()} + + def test_schedule_discovers_all_five_guests(self): + self.assertTrue(EXPECTED <= self.select()) + for name in NAMES: + self.assertTrue((TESTS / DNS / (name + '.java')).is_file()) + + def test_each_guest_change_selects_itself(self): + for name in NAMES: + with self.subTest(name=name): + self.assertIn(DNS + name, self.select(['src/test/java/' + DNS + name + '.java'])) + + def test_services_select_inherited_guests(self): + for service in ('ec2', 'ecs', 'route53', 'cloudmap'): + expected = {name for name in EXPECTED if service != 'ecs' or '/Ecs' in name} + with self.subTest(service=service): + selected = self.select(['src/main/java/io/floci/aws/services/' + service + '/Service.java']) + self.assertEqual(expected, selected & EXPECTED) + + def test_base_guest_change_selects_inherited_guests(self): + for kind in ('Ec2', 'Ecs'): + with self.subTest(kind=kind): + expected = {name for name in EXPECTED if '/' + kind in name} + base = 'src/test/java/' + DNS + kind + 'PrivateDnsGuestDockerNightlyIntegrationTest.java' + self.assertEqual(expected, self.select([base]) & EXPECTED) + + def test_dns_implementation_selects_all_guests(self): + selected = self.select(['src/main/java/io/floci/aws/core/common/dns/EmbeddedDnsServer.java']) + self.assertEqual(EXPECTED, selected & EXPECTED) + + def test_each_guest_prefetches_python_and_helper_base(self): + images = (TESTS / 'io/floci/aws/testing/TestImages.java').read_text() + python_image = images.split('PYTHON_ALPINE = "', 1)[1].split('"', 1)[0] + for name in NAMES: + with self.subTest(name=name), tempfile.TemporaryDirectory() as directory: + temp = Path(directory) + docker = temp / 'docker' + docker.write_text('#!/bin/sh\nprintf "%s\\n" "$3" >> "$PULLS"\n') + docker.chmod(0o755) + shard = temp / 'shard.txt' + shard.write_text(DNS + name + '\n') + pulls = temp / 'pulls.txt' + pulls.write_text('') + log = temp / 'prefetch.log' + env = dict(os.environ, PATH=str(temp) + ':' + os.environ['PATH'], + PULLS=str(pulls), PREFETCH_LOG=str(log)) + subprocess.run(['bash', '.github/ci/prefetch-images.sh', str(shard)], cwd=ROOT, + env=env, capture_output=True, text=True, check=True) + self.assertEqual({python_image, 'alpine:3.21'}, set(pulls.read_text().splitlines())) + self.assertNotIn('stale prefetch key', log.read_text()) + + if __name__ == '__main__': unittest.main() diff --git a/.github/workflows/nightly-checks.yml b/.github/workflows/nightly-checks.yml index d7286123fe..710fabb9e5 100644 --- a/.github/workflows/nightly-checks.yml +++ b/.github/workflows/nightly-checks.yml @@ -27,6 +27,7 @@ on: - 'src/main/java/io/floci/aws/config/**' - 'src/main/java/io/floci/aws/services/**' - 'src/main/java/io/floci/aws/core/common/docker/**' + - 'src/main/java/io/floci/aws/core/common/dns/**' permissions: contents: read diff --git a/docs/services/cloudmap.md b/docs/services/cloudmap.md index e6ada40c57..0233b0aa29 100644 --- a/docs/services/cloudmap.md +++ b/docs/services/cloudmap.md @@ -36,6 +36,14 @@ ignored. These existing filter limitations are unchanged. ### DNS resolution +For a querying workload with a known VPC, private namespace answers require an +association with the namespace's backing Route 53 zone. Additional associations +and their removal take effect on subsequent queries. An unrelated known VPC cannot +read private registrations. Callers without a known VPC retain unscoped private +answers for compatibility. Conflicting runtime identities return DNS REFUSED +before any record lookup or forwarding. The most specific visible private zone wins, and its +negative answers do not fall back to a public namespace. + A DNS namespace is answerable, not just storable. Floci's embedded DNS server resolves `.` to the `AWS_INSTANCE_IPV4` of the instances registered under that service, one A record each, so a container that uses Floci diff --git a/docs/services/route53.md b/docs/services/route53.md index 4695b47227..5d74c95e09 100644 --- a/docs/services/route53.md +++ b/docs/services/route53.md @@ -64,9 +64,10 @@ Route53 emulation supporting hosted zones, reusable delegation sets, resource re Floci resolves private hosted zone DNS records directly through its embedded DNS server on port 53. Cluster containers (such as EKS k3s containers) and workloads wired to embedded DNS automatically query Floci as their primary resolver. +- **Workload Origins**: EC2 uses its runtime metadata address registrations, including address reconciliation and removal. ECS `awsvpc` tasks register their actual container or shared-namespace addresses and revoke them on failed launch, stop, and cleanup. Bridge and host tasks use the VPC of their registered, running EC2 container instance when that instance resolves in the task account and region. DNS lookup does not inspect Docker. A workload without a known VPC does not borrow a default VPC. Conflicting runtime origins return DNS REFUSED before record lookup or forwarding, rather than using the unknown-caller fallback. - **Record Types**: Resolves IPv4 `A` records (including `CNAME` and `ALIAS` target chasing across private zones, EC2 internal names, and external hostnames). A target that is one of Floci's own names, under `localhost.floci.io`, `localhost.localstack.cloud`, `FLOCI_HOSTNAME` or a `FLOCI_DNS_EXTRA_SUFFIXES` suffix, resolves to Floci's container IP, the address the embedded DNS server answers that name with. When a private CNAME targets a public hostname, Floci resolves the target addresses off the event loop so container stub resolvers succeed. Multiple values are returned as separate answers. Simple private `SRV` record sets also resolve, preserving each value's priority, weight (including zero), port, target, and the record set TTL. The target `.` encodes an unavailable service. Malformed SRV values and SRV sets requiring routing policies or health evaluation return REFUSED; SRV CNAME chasing is not implemented. - **TTL and Negative Answers**: Answers carry the record set's `TTL`. A chased `CNAME` chain is flattened to `A` records, so it answers with the shortest TTL in the chain; an alias answers with its target's TTL, and an alias or `CNAME` to a name outside the private zones answers with at most 60 seconds, since Floci cannot see that target's TTL. A name absent from the zone receives NXDOMAIN; a name that exists without the requested record type (only `TXT`, for example, or only records beneath it) receives NOERROR with no answers. A private `CNAME` chain preserves that distinction from its target, including after the target is created or deleted. A wildcard record such as `*.example.internal` answers only when neither the name nor an ancestor closer than the wildcard exists, so a record at `api.team.example.internal` keeps the wildcard from answering for `team.example.internal` or anything beneath it. -- **Zone Visibility and Fallthrough**: Private hosted zones (created with a VPC association) provide IPv4 and SRV resolution. Public zones support the authoritative record types described below; unowned external domains fall through to upstream forwarders. Because the standard DNS wire protocol carries no caller VPC identifier, Floci resolves across private zones without filtering by account or VPC ID. +- **Zone Visibility and Fallthrough**: The querying managed workload identifies the caller account, region and VPC. Private answers, including aliases and CNAMEs, use only zones associated with that VPC. Association filtering happens before choosing the most specific zone. An identified but unassociated caller uses public DNS. Callers without a known VPC retain unscoped private-zone and Cloud Map answers for compatibility, without borrowing a default VPC; an associated private zone with no matching record answers negatively without falling back to public records. Association and disassociation changes apply to subsequent queries. Cloud Map uses the same backing-zone visibility rules. - **Resolver Rule Precedence**: A Route 53 Resolver rule associated with the querying container's VPC takes precedence over a private hosted zone that matches the same name, as it does in AWS: the query is forwarded to the rule's targets instead of answered from the zone. See [Route 53 Resolver](route53resolver.md#resolver-rules-and-dns-resolution). - **Zero-Restart Propagation**: Record changes via `ChangeResourceRecordSets` take effect immediately without restarts. - **Kubernetes and external-dns Compatibility**: In-cluster controllers like `external-dns` provisioning Route 53 private records for Services or Ingresses are immediately resolvable. diff --git a/src/main/java/io/floci/aws/core/common/dns/DnsRecordSource.java b/src/main/java/io/floci/aws/core/common/dns/DnsRecordSource.java index 3eaa426281..8f2d585b4d 100644 --- a/src/main/java/io/floci/aws/core/common/dns/DnsRecordSource.java +++ b/src/main/java/io/floci/aws/core/common/dns/DnsRecordSource.java @@ -28,6 +28,18 @@ public interface DnsRecordSource { return Optional.empty(); } + /** A null origin identifies a query outside any known VPC. */ + default Optional resolveAuthoritative(String name, int type, DnsClientVpcSource.ClientVpc origin) { + return resolveAuthoritative(name, type); + } + + /** Carries the listener address and querying VPC through authoritative lookup. */ + default Optional resolveAuthoritative(String name, int type, String listenerAddress, + DnsClientVpcSource.ClientVpc origin) { + return origin == null ? resolveAuthoritative(name, type, listenerAddress) + : resolveAuthoritative(name, type, origin); + } + /** * Resolves a query name to IPv4 addresses and their TTL. An empty optional means this * source does not own the name. The name arrives without a trailing dot and in the case the client sent. @@ -39,4 +51,9 @@ public interface DnsRecordSource { return resolveIpv4(name).map(answer -> type == 1 ? answer : answer.nameExists() ? DnsAnswer.noData() : DnsAnswer.nxDomain()); } + + /** Private record sources must restrict their answers to the querying VPC's associations. */ + default Optional resolve(String name, int type, DnsClientVpcSource.ClientVpc origin) { + return resolve(name, type); + } } diff --git a/src/main/java/io/floci/aws/core/common/dns/EmbeddedDnsServer.java b/src/main/java/io/floci/aws/core/common/dns/EmbeddedDnsServer.java index a9aafada0c..2ff13842ed 100644 --- a/src/main/java/io/floci/aws/core/common/dns/EmbeddedDnsServer.java +++ b/src/main/java/io/floci/aws/core/common/dns/EmbeddedDnsServer.java @@ -446,14 +446,19 @@ public class EmbeddedDnsServer { * than one question, a class other than IN, or a non-standard opcode or flag. */ QueryPlan planQuery(String name, String clientAddress, String myIp, int type, boolean standardQuery) { - Optional stored = resolveFromRecordSources(name, type, true, myIp); + ClientOrigin clientOrigin = originForClient(clientAddress); + if (clientOrigin.conflicting()) { + return QueryPlan.answering(DnsAnswer.refused()); + } + DnsClientVpcSource.ClientVpc origin = clientOrigin.vpc(); + Optional stored = resolveFromRecordSources(name, type, true, myIp, origin); Optional emulatorName = resolveEmulatorName(name, myIp, type); if (emulatorName.isPresent() && stored.isEmpty()) { return QueryPlan.answering(emulatorName.orElseThrow()); } // A rule steers the name whatever the query asks about it, so this is deliberately not // gated on the record type: the raw query is relayed to the rule's resolvers as it stands. - Optional rule = matchingRule(name, clientAddress); + Optional rule = matchingRule(name, origin); if (rule.isPresent() && rule.orElseThrow().forwards()) { return QueryPlan.forwardingTo(rule.orElseThrow().targets()); } @@ -461,7 +466,7 @@ public class EmbeddedDnsServer { && stored.filter(answer -> answer.responseCode() == 5).isPresent()) { return QueryPlan.answering(emulatorName.orElseThrow()); } - return stored.or(() -> resolveFromRecordSources(name, type)) + return stored.or(() -> resolveFromRecordSources(name, type, false, myIp, origin)) .map(QueryPlan::answering).orElse(QueryPlan.UPSTREAM); } @@ -481,14 +486,13 @@ public class EmbeddedDnsServer { * than allowed to fail the query, which is how {@link #resolveFromRecordSources} treats one too. */ Optional matchingRule(String name, String clientAddress) { - if (forwardingRuleSources == null || name == null || name.isBlank()) { + return matchingRule(name, originForClient(clientAddress).vpc()); + } + + private Optional matchingRule(String name, DnsClientVpcSource.ClientVpc origin) { + if (forwardingRuleSources == null || name == null || name.isBlank() || origin == null) { return Optional.empty(); } - Optional clientVpc = vpcForClient(clientAddress); - if (clientVpc.isEmpty()) { - return Optional.empty(); - } - DnsClientVpcSource.ClientVpc origin = clientVpc.orElseThrow(); DnsForwardingRule best = null; for (DnsForwardingRuleSource source : forwardingRuleSources) { try { @@ -509,23 +513,31 @@ public class EmbeddedDnsServer { return Optional.ofNullable(best); } - private Optional vpcForClient(String clientAddress) { + private record ClientOrigin(DnsClientVpcSource.ClientVpc vpc, boolean conflicting) { + } + + private ClientOrigin originForClient(String clientAddress) { if (clientVpcSources == null || clientAddress == null || clientAddress.isBlank()) { - return Optional.empty(); + return new ClientOrigin(null, false); } + DnsClientVpcSource.ClientVpc result = null; for (DnsClientVpcSource source : clientVpcSources) { try { Optional clientVpc = source.vpcForClient(clientAddress.trim()); if (clientVpc != null && clientVpc.isPresent() && isUsableOrigin(clientVpc.orElseThrow())) { - return clientVpc; + DnsClientVpcSource.ClientVpc found = clientVpc.orElseThrow(); + if (result != null && !result.equals(found)) { + return new ClientOrigin(null, true); + } + result = found; } } catch (Exception e) { LOG.debugv("DNS client VPC source {0} failed for {1}: {2}", source.getClass().getSimpleName(), clientAddress, e.getMessage()); } } - return Optional.empty(); + return new ClientOrigin(result, false); } private static boolean isUsableOrigin(DnsClientVpcSource.ClientVpc clientVpc) { @@ -548,6 +560,12 @@ public class EmbeddedDnsServer { private Optional resolveFromRecordSources( String name, int type, boolean authoritative, String listenerAddress) { + return resolveFromRecordSources(name, type, authoritative, listenerAddress, null); + } + + private Optional resolveFromRecordSources(String name, int type, boolean authoritative, + String listenerAddress, + DnsClientVpcSource.ClientVpc origin) { if (recordSources == null) { return Optional.empty(); } @@ -558,8 +576,8 @@ public class EmbeddedDnsServer { Optional empty = Optional.empty(); for (DnsRecordSource source : recordSources) { try { - Optional answer = authoritative ? source.resolveAuthoritative(name, type, listenerAddress) - : source.resolve(name, type); + Optional answer = authoritative ? source.resolveAuthoritative(name, type, listenerAddress, origin) + : source.resolve(name, type, origin); if (answer != null && answer.isPresent()) { if (answer.get().isEmpty()) { if (empty.isEmpty() || (!empty.get().nameExists() && answer.get().nameExists())) { diff --git a/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java index 8d702cb18f..5c7da84623 100644 --- a/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java +++ b/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java @@ -903,9 +903,27 @@ public class ContainerLifecycleManager { } } + /** Reports a confirmed stop before removal or log draining can block. */ + public boolean stopAndConfirmRemoved(String containerId, Closeable logStream, int stopTimeoutSeconds, + boolean removeAnonymousVolumes, Runnable onStopped) { + try { + stopAndRemoveStrict(containerId, logStream, stopTimeoutSeconds, removeAnonymousVolumes, onStopped); + return true; + } catch (RuntimeException e) { + LOG.warnv("Container {0} was not confirmed removed: {1}", containerId, e.getMessage()); + return false; + } + } + /** Strict teardown that can also reclaim the container's anonymous volumes. */ public void stopAndRemoveStrict(String containerId, Closeable logStream, int stopTimeoutSeconds, boolean removeAnonymousVolumes) { + stopAndRemoveStrict(containerId, logStream, stopTimeoutSeconds, removeAnonymousVolumes, () -> { }); + } + + /** Strict teardown with a notification as soon as the container cannot send more traffic. */ + public void stopAndRemoveStrict(String containerId, Closeable logStream, int stopTimeoutSeconds, + boolean removeAnonymousVolumes, Runnable onStopped) { LOG.infov("Stopping container {0}", containerId); Exception stopFailure = null; @@ -913,6 +931,7 @@ public class ContainerLifecycleManager { dockerClient.stopContainerCmd(containerId).withTimeout(stopTimeoutSeconds).exec(); } catch (NotFoundException e) { LOG.debugv("Container {0} not found (already removed)", containerId); + onStopped.run(); closeLogStreamIfPresent(logStream); return; } catch (NotModifiedException e) { @@ -922,6 +941,9 @@ public class ContainerLifecycleManager { stopFailure = e; LOG.warnv("Error stopping container {0}: {1}", containerId, e.getMessage()); } + if (stopFailure == null) { + onStopped.run(); + } readLastLogLines(logStream); try { @@ -949,6 +971,9 @@ public class ContainerLifecycleManager { } LOG.debugv("Container {0} is absent after its removal response failed", containerId); } + if (stopFailure != null) { + onStopped.run(); + } // Closed only once the container is stopped and gone, as in stopAndRemove, so the follower // can drain the final tail. closeLogStreamIfPresent(logStream); diff --git a/src/main/java/io/floci/aws/services/cloudmap/CloudMapDnsRecordSource.java b/src/main/java/io/floci/aws/services/cloudmap/CloudMapDnsRecordSource.java index 96e85a6b28..60c25e1fd0 100644 --- a/src/main/java/io/floci/aws/services/cloudmap/CloudMapDnsRecordSource.java +++ b/src/main/java/io/floci/aws/services/cloudmap/CloudMapDnsRecordSource.java @@ -1,6 +1,7 @@ package io.floci.aws.services.cloudmap; import io.floci.aws.core.common.dns.DnsAnswer; +import io.floci.aws.core.common.dns.DnsClientVpcSource.ClientVpc; import io.floci.aws.core.common.dns.DnsRecordSource; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -13,8 +14,8 @@ import java.util.Optional; *

Cloud Map's control plane accepts namespaces, services and instances and reads them back * correctly, but nothing answered DNS for {@code .}, so a container that * registered fine still failed to resolve its peers. Registering this with the embedded DNS - * server closes that gap for every caller of the embedded resolver, including containers Floci - * did not launch and instances registered directly through RegisterInstance. + * server closes that gap. Private namespace answers require the querying VPC's association with + * the namespace's backing Route 53 zone, including for instances registered through RegisterInstance. */ @ApplicationScoped public class CloudMapDnsRecordSource implements DnsRecordSource { @@ -28,11 +29,16 @@ public class CloudMapDnsRecordSource implements DnsRecordSource { @Override public Optional resolveIpv4(String name) { - return cloudMapService.resolveDnsNameIfOwned(name); + return resolve(name, 1, null); } @Override public Optional resolve(String name, int type) { - return cloudMapService.resolveDnsNameIfOwned(name, type); + return resolve(name, type, null); + } + + @Override + public Optional resolve(String name, int type, ClientVpc origin) { + return cloudMapService.resolveDnsNameIfOwned(name, type, origin); } } diff --git a/src/main/java/io/floci/aws/services/cloudmap/CloudMapService.java b/src/main/java/io/floci/aws/services/cloudmap/CloudMapService.java index 6f9d5d095f..91d8411d81 100644 --- a/src/main/java/io/floci/aws/services/cloudmap/CloudMapService.java +++ b/src/main/java/io/floci/aws/services/cloudmap/CloudMapService.java @@ -16,6 +16,7 @@ import io.floci.aws.core.common.Pagination; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.StoredResourceArns; import io.floci.aws.core.common.dns.DnsAnswer; +import io.floci.aws.core.common.dns.DnsClientVpcSource.ClientVpc; import io.floci.aws.core.common.dns.DnsRecord; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageBackend; @@ -42,6 +43,7 @@ import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.Executors; @@ -509,6 +511,20 @@ public class CloudMapService implements StoredResourceArns { } public Optional resolveDnsNameIfOwned(String queryName, int type) { + return resolveDnsNameIfOwned(queryName, type, dnsNamespacesByLongestName()); + } + + public Optional resolveDnsNameIfOwned(String queryName, int type, ClientVpc origin) { + Set privateZones = route53Service.privateDnsZoneIds(queryName, origin); + List visible = dnsNamespacesByLongestName().stream() + .filter(namespace -> "DNS_PRIVATE".equals(namespace.getType()) + ? privateZones.contains(namespace.getHostedZoneId()) + : privateZones.isEmpty()) + .toList(); + return resolveDnsNameIfOwned(queryName, type, visible); + } + + private Optional resolveDnsNameIfOwned(String queryName, int type, List namespaces) { if (queryName == null || queryName.isBlank()) { return Optional.empty(); } @@ -519,7 +535,7 @@ public class CloudMapService implements StoredResourceArns { String matchedNamespaceName = null; boolean nameExists = false; - for (Namespace namespace : dnsNamespacesByLongestName()) { + for (Namespace namespace : namespaces) { String namespaceName = namespace.getName().toLowerCase(Locale.ROOT); String suffix = "." + namespaceName; boolean apex = name.equals(namespaceName); diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java b/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java index 33154afae5..9f5e385492 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2ContainerManager.java @@ -29,6 +29,7 @@ import io.floci.aws.core.common.docker.PortAllocator; import io.floci.aws.core.common.docker.RetryingTarCopier; import io.floci.aws.core.common.docker.UserDataPipeline; import io.floci.aws.services.ec2.Ec2InstanceTypeCatalog.CatalogInstanceType; +import io.floci.aws.services.ec2.Ec2MetadataServer.DnsSuspension; import io.floci.aws.services.ec2.model.GroupIdentifier; import io.floci.aws.services.ec2.model.Instance; import io.floci.aws.services.ec2.model.InstanceNetworkInterface; @@ -1176,8 +1177,10 @@ public class Ec2ContainerManager { portForwardManager.unpublishAll(instance); try { dockerClient.stopContainerCmd(containerId).withTimeout(5).exec(); - } catch (NotFoundException e) { - // already gone + metadataServer.suspendDns(instance); + } catch (NotFoundException | NotModifiedException ignored) { + // The workload is confirmed absent or already stopped. + metadataServer.suspendDns(instance); } catch (Exception e) { LOG.warnv("Error stopping EC2 container {0} on shutdown: {1}", containerId, e.getMessage()); } @@ -1226,10 +1229,10 @@ public class Ec2ContainerManager { portForwardManager.unpublishAll(instance); try { dockerClient.stopContainerCmd(containerId).withTimeout(30).exec(); - } catch (NotFoundException ignored) { - // An already removed container needs no further stop. - } catch (NotModifiedException ignored) { - // An already stopped container, such as a guest that powered itself off, needs no stop. + metadataServer.suspendDns(instance); + } catch (NotFoundException | NotModifiedException ignored) { + // The workload is confirmed absent or already stopped. + metadataServer.suspendDns(instance); } catch (Exception e) { LOG.warnv("Error stopping EC2 container {0}: {1}", containerId, e.getMessage()); } @@ -1264,6 +1267,8 @@ public class Ec2ContainerManager { instance.setState(pending); submitLifecycleOperation(containerId, () -> RequestScopes.runAs(accountId, instance.getRegion(), () -> { boolean setUpMetadataEndpoint = false; + boolean confirmedRunning = false; + DnsSuspension dnsSuspension = metadataServer.suspendDns(instance); String protectedMetadataAddress = null; boolean retainedMetadataRegistration = false; try { @@ -1287,6 +1292,7 @@ public class Ec2ContainerManager { Thread.sleep(500); } } + confirmedRunning = running; // A protected workload shares the helper's namespace, so it has no Docker network // attachment of its own to rediscover: the helper keeps the transport address // across the workload's stop/start, exactly as launch used it. @@ -1336,6 +1342,9 @@ public class Ec2ContainerManager { rollbackProtectedMetadataRegistration(instance, protectedMetadataAddress, retainedMetadataRegistration); return; } + if (confirmedRunning) { + metadataServer.resumeDns(instance, dnsSuspension); + } persist(instance); watchForGuestShutdown(instance, containerId); if (postStart != null) { @@ -1441,7 +1450,14 @@ public class Ec2ContainerManager { && stillDeclared.test(region, instanceId)) { continue; } - lifecycleManager.removeIfExists(container.getId()); + try { + lifecycleManager.removeIfExistsStrict(container.getId()); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not remove orphaned EC2 container {0}; retaining its DNS origin", + container.getId()); + continue; + } + metadataServer.suspendContainerDns(container.getId()); removed++; LOG.infov("Reconciled orphaned EC2 container {0} (instance {1}) left by a previous run", container.getId(), String.valueOf(instanceId)); @@ -1482,6 +1498,7 @@ public class Ec2ContainerManager { return false; } String containerId = instance.getDockerContainerId(); + DnsSuspension dnsSuspension = metadataServer.dnsSuspension(instance); if (!lifecycleManager.isContainerRunning(containerId)) { return false; } @@ -1509,6 +1526,7 @@ public class Ec2ContainerManager { metadataServer.registerContainer(containerIp, instance.getInstanceId(), instance); refreshImdsSourceRegistration(instance, containerId, containerIp); refreshMetadataAddresses(instance, containerId); + metadataServer.resumeDns(instance, dnsSuspension); return true; } @@ -1810,6 +1828,7 @@ public class Ec2ContainerManager { firewallEniId = instance.getNetworkInterfaces() == null || instance.getNetworkInterfaces().isEmpty() ? null : instance.getNetworkInterfaces().getFirst().getNetworkInterfaceId(); instance.setState(InstanceState.shuttingDown()); + metadataServer.revokeInstanceCredentials(instance); // In-flight lookups no longer match and publish nothing; later ones see the state. serviceNetworkRetries.remove(instance.getInstanceId()); serviceNetworkLookups.remove(instance.getInstanceId()); @@ -1821,8 +1840,13 @@ public class Ec2ContainerManager { cleanupStep(instance, "port forwards", () -> portForwardManager.unpublishAll(instance)); if (containerId != null) { containerGone = removeContainer(containerId); + if (containerGone) { + metadataServer.suspendDns(instance); + } // iptables/veth teardown lags behind container removal; prevents port-reuse conflicts. pause(500); + } else { + metadataServer.suspendDns(instance); } if (firewallManager != null && firewallManager.enabled() && firewallEniId != null) { cleanupStep(instance, "firewall registration", () -> firewallManager.unregister(firewallEniId)); @@ -1830,17 +1854,17 @@ public class Ec2ContainerManager { if (sshHostPort > 0) { cleanupStep(instance, "SSH host port", () -> portAllocator.release(sshHostPort)); } - cleanupStep(instance, "metadata registrations", () -> { - metadataServer.unregisterContainer(containerIp, instance); - metadataServer.unregisterContainer(imdsSourceIp, instance); - metadataServer.unregisterInstance(instance); - }); - // Give the address back only now that the container is gone: releasing it while - // Docker still holds the endpoint would hand the same IP to the next launch and - // have Docker refuse it. - cleanupStep(instance, "private address", () -> vpcNetworkManager.releasePrivateIp( - instance.getOwnerId(), instance.getRegion(), instance.getSubnetId(), - instance.getPrivateIpAddress())); + if (containerGone) { + cleanupStep(instance, "metadata registrations", () -> { + metadataServer.unregisterContainer(containerIp, instance); + metadataServer.unregisterContainer(imdsSourceIp, instance); + metadataServer.unregisterInstance(instance); + }); + // A surviving Docker endpoint still owns its address and transport identity. + cleanupStep(instance, "private address", () -> vpcNetworkManager.releasePrivateIp( + instance.getOwnerId(), instance.getRegion(), instance.getSubnetId(), + instance.getPrivateIpAddress())); + } } finally { // Whatever the teardown managed, the instance must not stay shutting-down: nothing // else would ever finish it, and a leftover container is collected on the next start. @@ -1898,10 +1922,15 @@ public class Ec2ContainerManager { boolean stopAndConfirm(Instance instance) { String containerId = instance.getDockerContainerId(); if (containerId == null) { + metadataServer.suspendDns(instance); return true; } stopForShutdown(instance); - return lifecycleManager.probeContainer(containerId) == ContainerLiveness.NOT_RUNNING; + boolean stopped = lifecycleManager.probeContainer(containerId) == ContainerLiveness.NOT_RUNNING; + if (stopped) { + metadataServer.suspendDns(instance); + } + return stopped; } /** diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2MetadataServer.java b/src/main/java/io/floci/aws/services/ec2/Ec2MetadataServer.java index 35eb250e87..45140ac79d 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2MetadataServer.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2MetadataServer.java @@ -3,6 +3,7 @@ package io.floci.aws.services.ec2; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AvailabilityZoneIds; import io.floci.aws.core.common.AwsRegions; +import io.floci.aws.core.common.dns.DnsClientVpcSource; import io.floci.aws.services.ec2.model.GroupIdentifier; import io.floci.aws.services.ec2.model.Instance; import io.floci.aws.services.ec2.model.InstanceNetworkInterface; @@ -31,12 +32,14 @@ import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Base64; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.WeakHashMap; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiFunction; @@ -51,7 +54,7 @@ import java.util.function.Function; * to obtain temporary credentials backed by the instance's IAM instance profile. */ @ApplicationScoped -public class Ec2MetadataServer { +public class Ec2MetadataServer implements DnsClientVpcSource { private static final Logger LOG = Logger.getLogger(Ec2MetadataServer.class); private static final DateTimeFormatter ISO = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'") @@ -70,6 +73,12 @@ public class Ec2MetadataServer { private final Map tokens = new ConcurrentHashMap<>(); /** IMDSv1 fallback: container bridge IP → Instance */ private final Map containerIpToInstance = new ConcurrentHashMap<>(); + /** IMDS registrations may survive a stopped workload in a retained helper namespace. */ + // Keep revocation visible to in-flight restarts without retaining discarded instances. + private final Map dnsSuspendedInstances = + Collections.synchronizedMap(new WeakHashMap<>()); + private final Set credentialsRevoked = Collections.newSetFromMap( + Collections.synchronizedMap(new WeakHashMap<>())); /** Cluster nodes whose instance-profile identity their registrar synthesizes rather than IAM holding it. */ private final Set synthesizedProfiles = ConcurrentHashMap.newKeySet(); /** The addresses of the relays that name each caller in X-Forwarded-For, which is read from them alone. */ @@ -122,7 +131,11 @@ public class Ec2MetadataServer { /** Called by Ec2ContainerManager after a container starts to register its IP. */ public void registerContainer(String containerIp, String instanceId, Instance instance) { if (containerIp != null && !containerIp.isBlank()) { - credentials.register(instance); + synchronized (instance) { + if (!credentialsRevoked.contains(instance)) { + credentials.register(instance); + } + } containerIpToInstance.put(containerIp, instance); LOG.debugv("IMDS: registered container {0} → instance {1}", containerIp, instanceId); } @@ -164,13 +177,73 @@ public class Ec2MetadataServer { public void unregisterInstance(Instance instance) { if (instance != null) { + suspendDns(instance); + containerIpToInstance.entrySet().removeIf(entry -> entry.getValue() == instance); synthesizedProfiles.remove(instance); credentials.unregister(instance); tokens.values().removeIf(token -> token.instance() == instance); - containerIpToInstance.entrySet().removeIf(entry -> entry.getValue() == instance); } } + /** Revoke guest authentication independently of its retained Docker address ownership. */ + void revokeInstanceCredentials(Instance instance) { + synchronized (instance) { + credentialsRevoked.add(instance); + credentials.unregister(instance); + tokens.values().removeIf(token -> token.instance() == instance); + } + } + + static final class DnsSuspension { + } + + DnsSuspension suspendDns(Instance instance) { + DnsSuspension suspension = new DnsSuspension(); + dnsSuspendedInstances.put(instance, suspension); + return suspension; + } + + void suspendContainerDns(String containerId) { + if (containerId == null || containerId.isBlank()) { + return; + } + for (Instance instance : containerIpToInstance.values()) { + synchronized (instance) { + if (containerId.equals(instance.getDockerContainerId())) { + suspendDns(instance); + } + } + } + } + + DnsSuspension dnsSuspension(Instance instance) { + return dnsSuspendedInstances.get(instance); + } + + void resumeDns(Instance instance, DnsSuspension suspension) { + if (suspension != null) { + dnsSuspendedInstances.remove(instance, suspension); + } + } + + @Override + public Optional vpcForClient(String clientAddress) { + if (clientAddress == null || clientAddress.isBlank()) { + return Optional.empty(); + } + Instance instance = containerIpToInstance.get(clientAddress); + if (instance == null || dnsSuspendedInstances.containsKey(instance) || instance.getOwnerId() == null || instance.getOwnerId().isBlank() + || instance.getRegion() == null || instance.getRegion().isBlank() + || instance.getVpcId() == null || instance.getVpcId().isBlank()) { + return Optional.empty(); + } + ClientVpc origin = new ClientVpc(instance.getOwnerId(), instance.getRegion(), instance.getVpcId()); + if (dnsSuspendedInstances.containsKey(instance) || containerIpToInstance.get(clientAddress) != instance) { + return Optional.empty(); + } + return Optional.of(origin); + } + Optional registeredContainer(String containerIp) { return Optional.ofNullable(containerIpToInstance.get(containerIp)); } @@ -269,6 +342,7 @@ public class Ec2MetadataServer { credentials.clear(); tokens.clear(); containerIpToInstance.clear(); + dnsSuspendedInstances.clear(); synthesizedProfiles.clear(); forwarders.clear(); if (httpServer != null) { @@ -291,9 +365,13 @@ public class Ec2MetadataServer { Instance inst = resolveInstanceByIp(ctx); String token = UUID.randomUUID().toString().replace("-", ""); if (inst != null) { - Instant now = clock.instant(); - tokens.values().removeIf(existing -> existing.isExpiredAt(now)); - tokens.put(token, new SessionToken(inst, now.plusSeconds(ttlSeconds))); + synchronized (inst) { + if (!credentialsRevoked.contains(inst)) { + Instant now = clock.instant(); + tokens.values().removeIf(existing -> existing.isExpiredAt(now)); + tokens.put(token, new SessionToken(inst, now.plusSeconds(ttlSeconds))); + } + } } else { LOG.debugv("IMDS: token requested from {0}, which is not a registered EC2 container; " @@ -654,7 +732,8 @@ public class Ec2MetadataServer { // ── Instance resolution ─────────────────────────────────────────────────── private Instance resolveInstanceByIp(RoutingContext ctx) { - return containerIpToInstance.get(callerAddress(ctx)); + Instance instance = containerIpToInstance.get(callerAddress(ctx)); + return instance != null && credentialsRevoked.contains(instance) ? null : instance; } // The caller's address: the request's own, or the one a trusted relay names for its caller. @@ -683,7 +762,7 @@ public class Ec2MetadataServer { } private Instance resolveInstance(RoutingContext ctx) { - Instance inst = containerIpToInstance.get(callerAddress(ctx)); + Instance inst = resolveInstanceByIp(ctx); // IMDSv2: a presented token must be valid; an invalid or expired one gets 401 so the // caller fetches a new token. A token is not valid on another instance, so a caller whose @@ -693,7 +772,8 @@ public class Ec2MetadataServer { String token = ctx.request().getHeader("x-aws-ec2-metadata-token"); if (token != null && !token.isBlank()) { SessionToken session = tokens.get(token); - if (session != null && !session.isExpiredAt(clock.instant())) { + if (session != null && !credentialsRevoked.contains(session.instance()) + && !session.isExpiredAt(clock.instant())) { if (inst != null && !Objects.equals(inst.getInstanceId(), session.instance().getInstanceId())) { ctx.response().setStatusCode(401).end(); return null; diff --git a/src/main/java/io/floci/aws/services/ecs/EcsService.java b/src/main/java/io/floci/aws/services/ecs/EcsService.java index 18b75e76b1..a2507cc87c 100644 --- a/src/main/java/io/floci/aws/services/ecs/EcsService.java +++ b/src/main/java/io/floci/aws/services/ecs/EcsService.java @@ -12,6 +12,7 @@ import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.RequestScopes; import io.floci.aws.core.common.Resettable; import io.floci.aws.core.common.StoredResourceArns; +import io.floci.aws.core.common.dns.DnsClientVpcSource.ClientVpc; import io.floci.aws.core.resource.ExplorerResource; import io.floci.aws.core.resource.ResourceProvider; import io.floci.aws.core.resource.SupportedResourceType; @@ -1744,6 +1745,22 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab * StartTask run this on the task launcher once they have answered; the service scheduler runs * it inline. A StopTask that came first lands the task STOPPED without starting anything. */ + private EcsTaskHandle startTaskContainers(EcsTask task, TaskDefinition definition, + List overrides, String region) { + if (definition.getNetworkMode() != NetworkMode.awsvpc && definition.getNetworkMode() != NetworkMode.none + && task.getContainerInstanceArn() != null) { + ContainerInstance host = resolveContainerInstance(task.getClusterArn(), task.getContainerInstanceArn()); + if (host != null) { + Optional origin = containerManager.vpcForInstance( + taskAccountId(task.getTaskArn()), region, host.getEc2InstanceId()); + if (origin.isPresent()) { + return containerManager.startTask(task, definition, overrides, region, origin.orElseThrow()); + } + } + } + return containerManager.startTask(task, definition, overrides, region); + } + private void launchTask(EcsCluster cluster, EcsTask task, TaskDefinition taskDef, List containerOverrides, String region) { String taskArn = task.getTaskArn(); @@ -1774,7 +1791,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab "the containers a previous run of Floci left on the Docker daemon could not be removed yet"); } task.setPullStartedAt(Instant.now()); - EcsTaskHandle handle = containerManager.startTask(task, taskDef, containerOverrides, region); + EcsTaskHandle handle = startTaskContainers(task, taskDef, containerOverrides, region); task.setPullStoppedAt(Instant.now()); boolean stopRequested; synchronized (task) { @@ -5994,6 +6011,10 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab try { containerManager.stopTaskAndCollectExitCodes(claimed); + EcsTask task = tasks.get(taskArn); + if (task != null) { + containerManager.releaseTaskNetwork(task, taskRegion(task)); + } } finally { // A task can be reported STOPPED even if Docker rejected both teardown attempts. // Keep pending log readers and task volumes for later cleanup attempts. diff --git a/src/main/java/io/floci/aws/services/ecs/container/EcsContainerManager.java b/src/main/java/io/floci/aws/services/ecs/container/EcsContainerManager.java index ab5305f822..3f2de73b58 100644 --- a/src/main/java/io/floci/aws/services/ecs/container/EcsContainerManager.java +++ b/src/main/java/io/floci/aws/services/ecs/container/EcsContainerManager.java @@ -8,6 +8,7 @@ import com.github.dockerjava.api.command.ListVolumesResponse; import com.github.dockerjava.api.command.RemoveContainerCmd; import com.github.dockerjava.api.command.StatsCmd; import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.exception.NotModifiedException; import com.github.dockerjava.api.model.ContainerNetwork; import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.LogConfig; @@ -19,6 +20,7 @@ import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.Digests; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.dns.DnsClientVpcSource; import io.floci.aws.core.common.docker.ContainerBuilder; import io.floci.aws.core.common.docker.ContainerDetector; import io.floci.aws.core.common.docker.ContainerLifecycleManager; @@ -101,7 +103,7 @@ import java.util.stream.Stream; * Starts one Docker container per ContainerDefinition in a task and attaches logs to CloudWatch. */ @ApplicationScoped -public class EcsContainerManager { +public class EcsContainerManager implements DnsClientVpcSource { private static final Logger LOG = Logger.getLogger(EcsContainerManager.class); @@ -133,6 +135,8 @@ public class EcsContainerManager { /** The {@code FLUENT_HOST} the ECS agent gives an {@code awsvpc} task, whose containers share one namespace. */ private static final String FLUENT_AWSVPC_HOST = "127.0.0.1"; + private final Map> dnsOrigins = new ConcurrentHashMap<>(); + private final ContainerBuilder containerBuilder; private final ContainerLifecycleManager lifecycleManager; private final ContainerLogStreamer logStreamer; @@ -249,8 +253,19 @@ public class EcsContainerManager { return startTask(task, taskDef, containerOverrides, region, RetryingTarCopier.DEFAULT_BACKOFF_MS); } + public EcsTaskHandle startTask(EcsTask task, TaskDefinition taskDef, + List containerOverrides, String region, ClientVpc hostVpc) { + return startTask(task, taskDef, containerOverrides, region, RetryingTarCopier.DEFAULT_BACKOFF_MS, hostVpc); + } + EcsTaskHandle startTask(EcsTask task, TaskDefinition taskDef, List containerOverrides, String region, long firelensBackoffMillis) { + return startTask(task, taskDef, containerOverrides, region, firelensBackoffMillis, null); + } + + private EcsTaskHandle startTask(EcsTask task, TaskDefinition taskDef, + List containerOverrides, String region, long firelensBackoffMillis, + ClientVpc hostVpc) { if (!config.services().ecs().allowPrivilegedContainers() && taskDef.getContainerDefinitions().stream() .anyMatch(def -> Boolean.TRUE.equals(def.getPrivileged()))) { @@ -399,6 +414,14 @@ public class EcsContainerManager { sharedNamespace = prepareSharedNetwork(task, taskDef, region, taskId, taskRoleEndpoint); namespace = sharedNamespace; } + ClientVpc dnsVpc = taskDef.getNetworkMode() == NetworkMode.awsvpc + ? taskDnsVpc(task, region) : taskHostVpc(task, taskDef, region, hostVpc); + if (namespace != null && dnsVpc != null) { + DnsOwner namespaceOwner = new DnsOwner(task.getTaskArn(), namespace.helperId()); + registerDnsAddress(namespaceOwner, dnsVpc, namespace.transportAddress()); + registerDnsAddress(namespaceOwner, dnsVpc, namespace.transportIpv6Address()); + registerContainerDnsAddresses(task.getTaskArn(), dnsVpc, namespace.helperId()); + } for (ContainerDefinition def : launchOrder) { awaitDependencies(def, containerIds); String containerName = ContainerStorageHelper.dockerName(config, "ecs-" + taskId + "-" + def.getName()); @@ -607,6 +630,9 @@ public class EcsContainerManager { } containerIds.put(def.getName(), dockerId); + if (namespace == null && dnsVpc != null) { + registerContainerDnsAddresses(task.getTaskArn(), dnsVpc, dockerId); + } LOG.infov("Created ECS container {0} for task {1} container {2}", dockerId, taskId, def.getName()); @@ -641,6 +667,15 @@ public class EcsContainerManager { if (task.getNetworkInterfaceId() != null && protectedNetwork == null) { joinTaskVpcNetwork(task, taskDef, containerIds, sharedNamespace == null ? null : sharedNamespace.helperId(), region); + if (dnsVpc != null) { + if (sharedNamespace != null) { + registerContainerDnsAddresses(task.getTaskArn(), dnsVpc, sharedNamespace.helperId()); + } else { + for (String dockerId : containerIds.values()) { + registerContainerDnsAddresses(task.getTaskArn(), dnsVpc, dockerId); + } + } + } } } catch (Exception e) { EcsTaskHandle partial = new EcsTaskHandle(task.getTaskArn(), containerIds, logStreamsByContainerId, @@ -1153,6 +1188,86 @@ public class EcsContainerManager { .ifPresent(subnet -> task.setAvailabilityZone(subnet.getAvailabilityZone())); } + @Override + public Optional vpcForClient(String clientAddress) { + if (clientAddress == null) { + return Optional.empty(); + } + Map owners = dnsOrigins.get(clientAddress); + if (owners == null) { + return Optional.empty(); + } + Set vpcs = Set.copyOf(owners.values()); + return vpcs.size() == 1 ? Optional.of(vpcs.iterator().next()) : Optional.empty(); + } + + public Optional vpcForInstance(String accountId, String region, String instanceId) { + if (ec2Service == null || instanceId == null || instanceId.isBlank()) { + return Optional.empty(); + } + return ec2Service.findInstanceForAccount(accountId, region, instanceId) + .filter(instance -> instance.getState() != null && "running".equals(instance.getState().getName()) + && accountId.equals(instance.getOwnerId()) && region.equals(instance.getRegion()) + && instance.getVpcId() != null && !instance.getVpcId().isBlank()) + .map(instance -> new ClientVpc(accountId, region, instance.getVpcId())); + } + + private ClientVpc taskHostVpc(EcsTask task, TaskDefinition definition, String region, ClientVpc hostVpc) { + if (definition.getNetworkMode() == NetworkMode.none || hostVpc == null + || !region.equals(hostVpc.region()) || hostVpc.vpcId() == null || hostVpc.vpcId().isBlank() + || !AwsArnUtils.accountOrDefault(task.getTaskArn(), regionResolver.getAccountId()) + .equals(hostVpc.accountId())) { + return null; + } + return hostVpc; + } + + private ClientVpc taskDnsVpc(EcsTask task, String region) { + String vpcId = taskVpcId(task, region); + if (vpcId == null || vpcId.isBlank()) { + return null; + } + return new ClientVpc(AwsArnUtils.accountOrDefault(task.getTaskArn(), regionResolver.getAccountId()), + region, vpcId); + } + + private void registerContainerDnsAddresses(String taskArn, ClientVpc vpc, String dockerId) { + try { + InspectContainerResponse inspect = lifecycleManager.getDockerClient().inspectContainerCmd(dockerId).exec(); + if (inspect.getNetworkSettings() == null || inspect.getNetworkSettings().getNetworks() == null) { + return; + } + for (ContainerNetwork network : inspect.getNetworkSettings().getNetworks().values()) { + registerDnsAddress(new DnsOwner(taskArn, dockerId), vpc, network.getIpAddress()); + registerDnsAddress(new DnsOwner(taskArn, dockerId), vpc, network.getGlobalIPv6Address()); + } + } catch (RuntimeException e) { + LOG.warnv("Could not register DNS addresses of ECS container {0}: {1}", dockerId, e.getMessage()); + } + } + + private void registerDnsAddress(DnsOwner owner, ClientVpc vpc, String address) { + if (address != null && !address.isBlank()) { + dnsOrigins.compute(address, (key, previous) -> { + Map owners = new LinkedHashMap<>(previous == null ? Map.of() : previous); + owners.put(owner, vpc); + return Map.copyOf(owners); + }); + } + } + + private record DnsOwner(String taskArn, String containerId) {} + + private void unregisterContainerDns(String taskArn, String containerId) { + for (String address : dnsOrigins.keySet()) { + dnsOrigins.computeIfPresent(address, (key, previous) -> { + Map owners = new LinkedHashMap<>(previous); + owners.remove(new DnsOwner(taskArn, containerId)); + return owners.isEmpty() ? null : Map.copyOf(owners); + }); + } + } + /** * The VPC an awsvpc task's interface was created in, read from its subnet, or {@code null} * for a task without one or whose subnet is gone. @@ -1226,6 +1341,11 @@ public class EcsContainerManager { * Idempotent: the status is flipped first, so a second teardown path does nothing. */ public void releaseTaskNetwork(EcsTask task, String region) { + // A failed stop/removal can leave a workload or its namespace alive even after model teardown. + if (dnsOrigins.values().stream().anyMatch(owners -> owners.keySet().stream() + .anyMatch(owner -> owner.taskArn().equals(task.getTaskArn())))) { + return; + } String eniId = task.getNetworkInterfaceId(); if (eniId == null || ec2Service == null || ATTACHMENT_DELETED.equals(task.getAttachmentStatus())) { return; @@ -1490,6 +1610,13 @@ public class EcsContainerManager { firewallManager.removeProtectedNamespaceStrict(taskId); } } + for (Map owners : dnsOrigins.values()) { + for (DnsOwner owner : owners.keySet()) { + if (owner.taskArn().equals(handle.getTaskArn())) { + unregisterContainerDns(owner.taskArn(), owner.containerId()); + } + } + } handle.recordNamespaceHelperPending(false); } catch (RuntimeException e) { handle.recordNamespaceHelperPending(true); @@ -1570,13 +1697,17 @@ public class EcsContainerManager { for (Map.Entry entry : handle.getContainerIds().entrySet()) { // A container that survived removal still holds its link-local address, which must not // go to the next task. - if (lifecycleManager.stopAndConfirmRemoved(entry.getValue(), null, 5, true)) { + if (lifecycleManager.stopAndConfirmRemoved(entry.getValue(), null, 5, true, + () -> unregisterContainerDns(handle.getTaskArn(), entry.getValue()))) { handle.recordContainerRemoved(entry.getKey()); + unregisterContainerDns(handle.getTaskArn(), entry.getValue()); } else { + if (getExitCodeIfStopped(entry.getValue()) != null) { + unregisterContainerDns(handle.getTaskArn(), entry.getValue()); + } allRemoved = false; } } - cleanupProtectedNetwork(handle); new ArrayList<>(handle.getLogStreamsByContainerId().keySet()) .forEach(dockerId -> finalizeLogStream(handle, dockerId)); revokeTaskRoleCredentials(handle.getTaskArn()); @@ -1584,6 +1715,7 @@ public class EcsContainerManager { removeTaskVolumes(handle); try { removeNamespaceHelper(handle); + cleanupProtectedNetwork(handle); } catch (RuntimeException e) { // The handle now says the helper is pending, so the caller keeps it and the removal is // retried; its address stays reserved until then, the cheaper mistake. @@ -1617,12 +1749,19 @@ public class EcsContainerManager { lifecycleManager.getDockerClient().stopContainerCmd(dockerId) .withTimeout(handle.stopTimeoutFor(entry.getKey())).exec(); terminatedContainerIds.add(dockerId); - } catch (NotFoundException ignored) { + } catch (NotFoundException | NotModifiedException ignored) { terminatedContainerIds.add(dockerId); } catch (Exception e) { LOG.warnv("Error stopping ECS container {0}: {1}", dockerId, e.getMessage()); } + boolean stopConfirmed = terminatedContainerIds.contains(dockerId); + if (stopConfirmed) { + unregisterContainerDns(handle.getTaskArn(), dockerId); + } killIfStillRunning(dockerId); + if (!stopConfirmed && getExitCodeIfStopped(dockerId) != null) { + unregisterContainerDns(handle.getTaskArn(), dockerId); + } } // Phase 2: inspect exit codes, then remove. @@ -1648,9 +1787,11 @@ public class EcsContainerManager { remove.exec(); terminatedContainerIds.add(dockerId); handle.recordContainerRemoved(name); + unregisterContainerDns(handle.getTaskArn(), dockerId); } catch (NotFoundException ignored) { terminatedContainerIds.add(dockerId); handle.recordContainerRemoved(name); + unregisterContainerDns(handle.getTaskArn(), dockerId); } catch (Exception e) { LOG.warnv("Error removing ECS container {0}: {1}", dockerId, e.getMessage()); exitCodes.put(name, null); diff --git a/src/main/java/io/floci/aws/services/route53/Route53DnsRecordSource.java b/src/main/java/io/floci/aws/services/route53/Route53DnsRecordSource.java index 33cbd7f8aa..243f4583ba 100644 --- a/src/main/java/io/floci/aws/services/route53/Route53DnsRecordSource.java +++ b/src/main/java/io/floci/aws/services/route53/Route53DnsRecordSource.java @@ -4,6 +4,7 @@ import io.floci.aws.config.EmulatorConfig; import io.floci.aws.config.LocalStackParity; import io.floci.aws.core.common.DomainNames; import io.floci.aws.core.common.dns.DnsAnswer; +import io.floci.aws.core.common.dns.DnsClientVpcSource.ClientVpc; import io.floci.aws.core.common.dns.DnsLookupHelper; import io.floci.aws.core.common.dns.DnsRecord; import io.floci.aws.core.common.dns.DnsRecordSource; @@ -75,15 +76,25 @@ public class Route53DnsRecordSource implements DnsRecordSource { @Override public Optional resolveAuthoritative(String name, int type) { - return resolveAuthoritative(name, type, null); + return resolveAuthoritative(name, type, null, null); } @Override public Optional resolveAuthoritative(String name, int type, String listenerAddress) { + return resolveAuthoritative(name, type, listenerAddress, null); + } + + @Override + public Optional resolveAuthoritative(String name, int type, ClientVpc origin) { + return resolveAuthoritative(name, type, null, origin); + } + + @Override + public Optional resolveAuthoritative(String name, int type, String listenerAddress, ClientVpc origin) { if (name == null || name.isBlank() || (type != 1 && type != 2 && type != 6 && type != 16 && type != 28)) { return Optional.empty(); } - if (route53Service.isCoveredByPrivateZone(name)) { + if (route53Service.isCoveredByPrivateZone(name, origin)) { return Optional.empty(); } List zones = route53Service.publicDnsZones(name); @@ -178,20 +189,21 @@ public class Route53DnsRecordSource implements DnsRecordSource { @Override public Optional resolve(String name, int type) { - if (type != 33) { - return DnsRecordSource.super.resolve(name, type); - } - if (name == null || name.isBlank() || !route53Service.isCoveredByPrivateZone(name)) { + return resolve(name, type, null); + } + + private Optional resolveSrv(String name, ClientVpc origin) { + if (name == null || name.isBlank() || !route53Service.isCoveredByPrivateZone(name, origin)) { return Optional.empty(); } - List sets = route53Service.findPrivateRecordsForName(name); + List sets = route53Service.findPrivateRecordsForName(name, origin); DnsAnswer answer = buildRecords(name, sets.stream() .filter(set -> "SRV".equalsIgnoreCase(set.getType())).toList(), Route53DnsRecordSource::srvRecord, Route53DnsRecordSource::ttlOf); if (answer.responseCode() != 0 || !answer.isEmpty()) { return Optional.of(answer); } - return Optional.of(!sets.isEmpty() || route53Service.hasPrivateRecordsBeneath(name) + return Optional.of(!sets.isEmpty() || route53Service.hasPrivateRecordsBeneath(name, origin) ? DnsAnswer.noData() : DnsAnswer.nxDomain()); } @@ -236,20 +248,33 @@ public class Route53DnsRecordSource implements DnsRecordSource { @Override public Optional resolveIpv4(String name) { + return resolveIpv4(name, null); + } + + @Override + public Optional resolve(String name, int type, ClientVpc origin) { + if (type == 33) { + return resolveSrv(name, origin); + } + return resolveIpv4(name, origin).map(answer -> type == 1 ? answer + : answer.nameExists() ? DnsAnswer.noData() : DnsAnswer.nxDomain()); + } + + private Optional resolveIpv4(String name, ClientVpc origin) { if (name == null || name.isBlank()) { return Optional.empty(); } - if (!route53Service.isCoveredByPrivateZone(name)) { + if (!route53Service.isCoveredByPrivateZone(name, origin)) { return Optional.empty(); } - DnsAnswer answer = resolveAddresses(name, new HashSet<>(), 0); + DnsAnswer answer = resolveAddresses(name, new HashSet<>(), 0, origin); if (answer.addresses().size() > MAX_DNS_ANSWERS) { answer = DnsAnswer.records(answer.addresses().subList(0, MAX_DNS_ANSWERS), answer.ttlSeconds()); } return Optional.of(answer); } - private DnsAnswer resolveAddresses(String qname, Set visited, int depth) { + private DnsAnswer resolveAddresses(String qname, Set visited, int depth, ClientVpc origin) { if (depth > MAX_CNAME_DEPTH) { return DnsAnswer.noData(); } @@ -258,9 +283,9 @@ public class Route53DnsRecordSource implements DnsRecordSource { return DnsAnswer.noData(); } - List recordSets = route53Service.findPrivateRecordsForName(qname); + List recordSets = route53Service.findPrivateRecordsForName(qname, origin); if (recordSets.isEmpty()) { - return route53Service.hasPrivateRecordsBeneath(qname) ? DnsAnswer.noData() : DnsAnswer.nxDomain(); + return route53Service.hasPrivateRecordsBeneath(qname, origin) ? DnsAnswer.noData() : DnsAnswer.nxDomain(); } // 1. Direct A records @@ -281,8 +306,8 @@ public class Route53DnsRecordSource implements DnsRecordSource { if (alias != null && alias.getDnsName() != null && !alias.getDnsName().isBlank()) { String cleanAlias = DnsLookupHelper.normalizeTarget(alias.getDnsName()); // An alias record has no TTL of its own; Route 53 answers with the target's. - if (route53Service.isCoveredByPrivateZone(cleanAlias)) { - DnsAnswer target = resolveAddresses(cleanAlias, visited, depth + 1); + if (route53Service.isCoveredByPrivateZone(cleanAlias, origin)) { + DnsAnswer target = resolveAddresses(cleanAlias, visited, depth + 1, origin); if (!target.isEmpty()) { addresses.addAll(target.addresses()); ttl = Math.min(ttl, target.ttlSeconds()); @@ -311,8 +336,8 @@ public class Route53DnsRecordSource implements DnsRecordSource { // The answer is flattened to A records, so it can be cached only as long // as the shortest-lived record in the chain. int cnameTtl = ttlOf(rrs); - if (route53Service.isCoveredByPrivateZone(cleanTarget)) { - DnsAnswer targetAnswer = resolveAddresses(cleanTarget, visited, depth + 1); + if (route53Service.isCoveredByPrivateZone(cleanTarget, origin)) { + DnsAnswer targetAnswer = resolveAddresses(cleanTarget, visited, depth + 1, origin); if (targetAnswer.isEmpty()) { return targetAnswer; } diff --git a/src/main/java/io/floci/aws/services/route53/Route53Service.java b/src/main/java/io/floci/aws/services/route53/Route53Service.java index e46222d323..3c852fffb5 100644 --- a/src/main/java/io/floci/aws/services/route53/Route53Service.java +++ b/src/main/java/io/floci/aws/services/route53/Route53Service.java @@ -7,6 +7,7 @@ import io.floci.aws.core.common.DomainNames; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.RequestConditionSpelling; import io.floci.aws.core.common.Resettable; +import io.floci.aws.core.common.dns.DnsClientVpcSource.ClientVpc; import io.floci.aws.core.common.dns.DnsLookupHelper; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageBackend; @@ -36,9 +37,12 @@ import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; +import java.util.function.Predicate; +import java.util.stream.Collectors; @ApplicationScoped public class Route53Service implements Resettable, RequestConditionSpelling { @@ -806,36 +810,45 @@ public class Route53Service implements Resettable, RequestConditionSpelling { .toList(); } - public boolean isCoveredByPrivateZone(String qname) { - if (qname == null || qname.isBlank()) { - return false; - } - String normalizedQname = normalizeName(qname).toLowerCase(); - if (privateZoneNameCounts.isEmpty() - || privateZoneNameCounts.keySet().stream().noneMatch(z -> DomainNames.isWithin(normalizedQname, z))) { - return false; - } - for (OwnedZone owned : allHostedZonesAcrossAccounts()) { - HostedZone zone = owned.zone(); - if (!zone.isPrivateZone()) { - continue; - } - String zoneName = normalizeName(zone.getName()).toLowerCase(); - if (DomainNames.isWithin(normalizedQname, zoneName)) { - return true; - } - } - return false; + public boolean isCoveredByPrivateZone(String qname, ClientVpc origin) { + return !privateDnsZones(qname, origin).isEmpty(); } - public List findPrivateRecordsForName(String qname) { + /** Selects the most specific private zones, filtering associations when the caller VPC is known. */ + public Set privateDnsZoneIds(String qname, ClientVpc origin) { + return privateDnsZones(qname, origin).stream() + .map(owned -> owned.zone().getId()).collect(Collectors.toSet()); + } + + public List findPrivateRecordsForName(String qname, ClientVpc origin) { + List zones = privateDnsZones(qname, origin); + return zones.isEmpty() ? List.of() : findRecordsForName(normalizeName(qname).toLowerCase(), + zones.stream().map(owned -> getRecordsForZoneAcrossAccounts( + owned.accountId(), owned.zone().getId())).toList()); + } + + public boolean hasPrivateRecordsBeneath(String qname, ClientVpc origin) { + List zones = privateDnsZones(qname, origin); + if (zones.isEmpty()) { + return false; + } + String suffix = "." + normalizeName(qname).toLowerCase(); + return zones.stream().flatMap(owned -> getRecordsForZoneAcrossAccounts( + owned.accountId(), owned.zone().getId()).stream()) + .anyMatch(record -> normalizeName(record.getName()).toLowerCase().endsWith(suffix)); + } + + private List privateDnsZones(String qname, ClientVpc origin) { if (qname == null || qname.isBlank()) { return List.of(); } - return findRecordsForName(normalizeName(qname).toLowerCase(), - mostSpecificZones(normalizeName(qname).toLowerCase(), true).stream() - .map(owned -> getRecordsForZoneAcrossAccounts(owned.accountId(), owned.zone().getId())) - .toList()); + return mostSpecificZones(normalizeName(qname).toLowerCase(), true, owned -> origin == null + || owned.zone().getVpcAssociations().stream().anyMatch(association -> + origin.vpcId().equals(association.getVpcId()) + && origin.region().equals(association.getVpcRegion()) + && origin.accountId().equals(association.getOwnerAccountId() != null + ? association.getOwnerAccountId() + : resolveVpcOwnerAccount(association).orElse(owned.accountId())))); } private static List findRecordsForName(String normalizedQname, @@ -900,26 +913,6 @@ public class Route53Service implements Resettable, RequestConditionSpelling { return shared; } - /** - * Whether a private zone holds records beneath {@code qname} although none at it: an empty - * non-terminal, which exists in DNS and so answers NOERROR rather than NXDOMAIN. - */ - public boolean hasPrivateRecordsBeneath(String qname) { - if (qname == null || qname.isBlank()) { - return false; - } - String normalizedQname = normalizeName(qname).toLowerCase(); - String suffix = "." + normalizedQname; - for (OwnedZone owned : mostSpecificZones(normalizedQname, true)) { - for (ResourceRecordSet rrs : getRecordsForZoneAcrossAccounts(owned.accountId(), owned.zone().getId())) { - if (normalizeName(rrs.getName()).toLowerCase().endsWith(suffix)) { - return true; - } - } - } - return false; - } - record PublicDnsZone(String name, List matchingRecords, List records) {} List publicDnsZones(String qname) { @@ -940,6 +933,11 @@ public class Route53Service implements Resettable, RequestConditionSpelling { /** The longest containing zones, so a parent never answers for a more specific child. */ private List mostSpecificZones(String normalizedQname, boolean privateZone) { + return mostSpecificZones(normalizedQname, privateZone, owned -> true); + } + + private List mostSpecificZones(String normalizedQname, boolean privateZone, + Predicate visible) { Map names = zoneNameCounts(privateZone); if (names.isEmpty() || names.keySet().stream().noneMatch(z -> DomainNames.isWithin(normalizedQname, z))) { return List.of(); @@ -948,7 +946,7 @@ public class Route53Service implements Resettable, RequestConditionSpelling { int maxZoneLength = -1; for (OwnedZone owned : allHostedZonesAcrossAccounts()) { HostedZone zone = owned.zone(); - if (zone.isPrivateZone() != privateZone) { + if (zone.isPrivateZone() != privateZone || !visible.test(owned)) { continue; } String zoneName = normalizeName(zone.getName()).toLowerCase(); diff --git a/src/test/java/io/floci/aws/core/common/dns/CloudMapDnsPacketIntegrationTest.java b/src/test/java/io/floci/aws/core/common/dns/CloudMapDnsPacketIntegrationTest.java index 91dd3c3c78..aecac68787 100644 --- a/src/test/java/io/floci/aws/core/common/dns/CloudMapDnsPacketIntegrationTest.java +++ b/src/test/java/io/floci/aws/core/common/dns/CloudMapDnsPacketIntegrationTest.java @@ -1,5 +1,6 @@ package io.floci.aws.core.common.dns; +import io.floci.aws.config.EmulatorConfig; import io.floci.aws.services.cloudmap.CloudMapDnsRecordSource; import io.floci.aws.services.cloudmap.CloudMapService; import io.floci.aws.services.cloudmap.model.Service; @@ -20,6 +21,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; @@ -48,17 +50,32 @@ class CloudMapDnsPacketIntegrationTest { @Inject Vertx vertx; + @Inject + EmulatorConfig config; + + @Test + void conflictingRuntimeOriginsRefuseCloudMapRecordsAcrossTheWire() throws Exception { + String namespace = namespaceWithApiInstance(); + DnsClientVpcSource first = address -> Optional.of(new DnsClientVpcSource.ClientVpc( + config.defaultAccountId(), REGION, "vpc-first")); + DnsClientVpcSource second = address -> Optional.of(new DnsClientVpcSource.ClientVpc( + config.defaultAccountId(), REGION, "vpc-second")); + byte[] request = DnsTestQuery.query("api." + namespace, 1, 0x1234); + for (List sources : bothSourceOrders()) { + for (List providers : List.of(List.of(first, second), List.of(second, first))) { + byte[] response = query(new EmbeddedDnsServer(List.of(), sources, List.of(), providers), request); + assertEquals(5, ByteBuffer.wrap(response).getShort(2) & 15); + assertEquals(0, ByteBuffer.wrap(response).getShort(6)); + } + } + } + @Test void configuredTtlReachesTheDnsPacket() throws Exception { - String namespace = uniqueNamespace(); - String namespaceId = privateDnsNamespace(namespace); - Service service = cloudMapService.createService("api", namespaceId, null, null, - "{\"DnsRecords\":[{\"Type\":\"A\",\"TTL\":15}]}", null, null, null, Map.of(), REGION); - cloudMapService.registerInstance(service.getId(), "task-1", null, - Map.of("AWS_INSTANCE_IPV4", "172.31.0.6"), REGION); + String namespace = namespaceWithApiInstance(); byte[] request = DnsTestQuery.query("api." + namespace, 1, 0x1234); - byte[] response = query(new EmbeddedDnsServer(List.of(), List.of(cloudMapDnsRecordSource)), request); + byte[] response = query(serverForVpc(List.of(cloudMapDnsRecordSource)), request); ByteBuffer packet = ByteBuffer.wrap(response); assertEquals(0, packet.getShort(2) & 0x000F); @@ -68,6 +85,19 @@ class CloudMapDnsPacketIntegrationTest { Arrays.copyOfRange(response, request.length + 12, request.length + 16)); } + @Test + void unknownCallerRetainsPrivateCloudMapAnswersAcrossTheWire() throws Exception { + String namespace = namespaceWithApiInstance(); + byte[] request = DnsTestQuery.query("api." + namespace, 1, 0x1234); + for (List sources : bothSourceOrders()) { + byte[] response = query(new EmbeddedDnsServer(List.of(), sources, List.of(), List.of()), request); + assertEquals(0, ByteBuffer.wrap(response).getShort(2) & 15); + assertEquals(1, ByteBuffer.wrap(response).getShort(6)); + assertArrayEquals(new byte[]{(byte) 172, 31, 0, 6}, + Arrays.copyOfRange(response, response.length - 4, response.length)); + } + } + /** * The namespace's Route 53 zone covers the same names, and answers NXDOMAIN for a name it * has no record for, or NOERROR/NODATA for a name holding only another type (the TXT below). @@ -101,11 +131,9 @@ class CloudMapDnsPacketIntegrationTest { } private void assertBothSourceOrdersResolve(String namespace) throws Exception { - for (List sources : List.of( - List.of(route53DnsRecordSource, cloudMapDnsRecordSource), - List.of(cloudMapDnsRecordSource, route53DnsRecordSource))) { + for (List sources : bothSourceOrders()) { byte[] request = DnsTestQuery.query("both." + namespace, 1, 0x1234); - byte[] response = query(new EmbeddedDnsServer(List.of(), sources), request); + byte[] response = query(serverForVpc(sources), request); ByteBuffer packet = ByteBuffer.wrap(response); assertEquals(0, packet.getShort(2) & 0x000F); @@ -114,14 +142,13 @@ class CloudMapDnsPacketIntegrationTest { Arrays.copyOfRange(response, request.length + 12, request.length + 16)); // A name only Route 53 holds (as TXT) is NODATA for A, not Cloud Map's NXDOMAIN. - ByteBuffer txtOnly = ByteBuffer.wrap(query(new EmbeddedDnsServer(List.of(), sources), + ByteBuffer txtOnly = ByteBuffer.wrap(query(serverForVpc(sources), DnsTestQuery.query("txtonly." + namespace, 1, 0x1234))); assertEquals(0, txtOnly.getShort(2) & 0x000F); assertEquals(0, txtOnly.getShort(6)); } // A name neither source has is still NXDOMAIN. - byte[] missing = query(new EmbeddedDnsServer(List.of(), - List.of(route53DnsRecordSource, cloudMapDnsRecordSource)), + byte[] missing = query(serverForVpc(List.of(route53DnsRecordSource, cloudMapDnsRecordSource)), DnsTestQuery.query("nothere." + namespace, 1, 0x1234)); assertEquals(3, ByteBuffer.wrap(missing).getShort(2) & 0x000F); } @@ -135,7 +162,7 @@ class CloudMapDnsPacketIntegrationTest { cloudMapService.registerInstance(service.getId(), "task-1", null, Map.of("AWS_INSTANCE_IPV4", "172.31.0.6", "AWS_INSTANCE_PORT", "8080"), REGION); - byte[] response = query(new EmbeddedDnsServer(List.of(), List.of(cloudMapDnsRecordSource)), + byte[] response = query(serverForVpc(List.of(cloudMapDnsRecordSource)), DnsTestQuery.query("srvonly." + namespace, 1, 0x1234)); ByteBuffer packet = ByteBuffer.wrap(response); @@ -154,7 +181,7 @@ class CloudMapDnsPacketIntegrationTest { Map.of("AWS_INSTANCE_IPV4", "172.31.0.6", "AWS_INSTANCE_PORT", "8080"), REGION); byte[] request = DnsTestQuery.query("task-1.backend." + namespace, 1, 0x1234); - byte[] response = query(new EmbeddedDnsServer(List.of(), List.of(cloudMapDnsRecordSource)), request); + byte[] response = query(serverForVpc(List.of(cloudMapDnsRecordSource)), request); ByteBuffer packet = ByteBuffer.wrap(response); assertEquals(0, packet.getShort(2) & 0x000F); @@ -169,12 +196,28 @@ class CloudMapDnsPacketIntegrationTest { String namespace = uniqueNamespace(); privateDnsNamespace(namespace); - byte[] response = query(new EmbeddedDnsServer(List.of(), List.of(cloudMapDnsRecordSource)), + byte[] response = query(serverForVpc(List.of(cloudMapDnsRecordSource)), DnsTestQuery.query("missing." + namespace, 1, 0x1234)); assertEquals(3, ByteBuffer.wrap(response).getShort(2) & 0x000F); } + private String namespaceWithApiInstance() { + String namespace = uniqueNamespace(); + String namespaceId = privateDnsNamespace(namespace); + Service service = cloudMapService.createService("api", namespaceId, null, null, + "{\"DnsRecords\":[{\"Type\":\"A\",\"TTL\":15}]}", null, null, null, Map.of(), REGION); + cloudMapService.registerInstance(service.getId(), "task-1", null, + Map.of("AWS_INSTANCE_IPV4", "172.31.0.6"), REGION); + return namespace; + } + + private List> bothSourceOrders() { + return List.of( + List.of(route53DnsRecordSource, cloudMapDnsRecordSource), + List.of(cloudMapDnsRecordSource, route53DnsRecordSource)); + } + private String privateDnsNamespace(String name) { return cloudMapService.createPrivateDnsNamespace(name, "vpc-dns", null, null, Map.of(), REGION).getTargets().get("NAMESPACE"); @@ -187,7 +230,7 @@ class CloudMapDnsPacketIntegrationTest { cloudMapService.registerInstance(service.getId(), "task-1", null, Map.of("AWS_INSTANCE_IPV6", "2001:db8::1"), REGION); byte[] request = DnsTestQuery.query("typed." + namespace, 28, 0x1234); - byte[] response = query(new EmbeddedDnsServer(List.of(), List.of(cloudMapDnsRecordSource)), request); + byte[] response = query(serverForVpc(List.of(cloudMapDnsRecordSource)), request); ByteBuffer packet = ByteBuffer.wrap(response); assertEquals(1, packet.getShort(6)); assertEquals(28, packet.getShort(request.length + 2)); @@ -206,7 +249,7 @@ class CloudMapDnsPacketIntegrationTest { Map.of("AWS_INSTANCE_CNAME", "backend.example.com"), REGION); for (short type : new short[]{1, 5, 28}) { byte[] request = DnsTestQuery.query("typed." + namespace, type, 0x1234); - byte[] response = query(new EmbeddedDnsServer(List.of(), List.of(cloudMapDnsRecordSource)), request); + byte[] response = query(serverForVpc(List.of(cloudMapDnsRecordSource)), request); ByteBuffer packet = ByteBuffer.wrap(response); assertEquals(1, packet.getShort(6)); assertEquals(5, packet.getShort(request.length + 2)); @@ -223,7 +266,7 @@ class CloudMapDnsPacketIntegrationTest { cloudMapService.registerInstance(service.getId(), "task-1", null, Map.of("AWS_INSTANCE_IPV6", "2001:db8::2", "AWS_INSTANCE_PORT", "8080"), REGION); byte[] request = DnsTestQuery.query("typed." + namespace, 33, 0x1234); - byte[] response = query(new EmbeddedDnsServer(List.of(), List.of(cloudMapDnsRecordSource)), request); + byte[] response = query(serverForVpc(List.of(cloudMapDnsRecordSource)), request); ByteBuffer packet = ByteBuffer.wrap(response); assertEquals(1, packet.getShort(6)); assertEquals(33, packet.getShort(request.length + 2)); @@ -232,7 +275,7 @@ class CloudMapDnsPacketIntegrationTest { assertEquals(1, packet.getShort()); assertEquals(8080, packet.getShort()); assertEquals("task-1.typed." + namespace, EmbeddedDnsServer.readName(packet, response)); - byte[] address = query(new EmbeddedDnsServer(List.of(), List.of(cloudMapDnsRecordSource)), + byte[] address = query(serverForVpc(List.of(cloudMapDnsRecordSource)), DnsTestQuery.query("task-1.typed." + namespace, 28, 0x1234)); assertEquals(1, ByteBuffer.wrap(address).getShort(6)); } @@ -245,7 +288,7 @@ class CloudMapDnsPacketIntegrationTest { cloudMapService.registerInstance(service.getId(), "task-" + i, null, Map.of("AWS_INSTANCE_IPV4", "172.31.0." + i), REGION); } - byte[] response = query(new EmbeddedDnsServer(List.of(), List.of(cloudMapDnsRecordSource)), + byte[] response = query(serverForVpc(List.of(cloudMapDnsRecordSource)), DnsTestQuery.query("typed." + namespace, 1, 0x1234)); assertEquals(1, ByteBuffer.wrap(response).getShort(6)); } @@ -264,7 +307,7 @@ class CloudMapDnsPacketIntegrationTest { cloudMapService.registerInstance(service.getId(), "instance-with-long-name-" + i, null, Map.of("AWS_INSTANCE_IPV4", "192.0.2.1", "AWS_INSTANCE_PORT", "8080"), REGION); } - EmbeddedDnsServer dns = new EmbeddedDnsServer(List.of(), List.of(cloudMapDnsRecordSource)); + EmbeddedDnsServer dns = serverForVpc(List.of(cloudMapDnsRecordSource)); byte[] legacyQuery = DnsTestQuery.query("typed." + namespace, 33, 0x1234); byte[] legacy = query(dns, legacyQuery); ByteBuffer legacyPacket = ByteBuffer.wrap(legacy); @@ -313,6 +356,13 @@ class CloudMapDnsPacketIntegrationTest { return "dnspacket" + UUID.randomUUID().toString().substring(0, 8) + ".internal"; } + private EmbeddedDnsServer serverForVpc(List sources) { + DnsClientVpcSource clients = address -> "127.0.0.1".equals(address) + ? Optional.of(new DnsClientVpcSource.ClientVpc(config.defaultAccountId(), REGION, "vpc-dns")) + : Optional.empty(); + return new EmbeddedDnsServer(List.of(), sources, List.of(), List.of(clients)); + } + private byte[] query(EmbeddedDnsServer dns, byte[] request) throws Exception { DatagramSocket server = vertx.createDatagramSocket(new DatagramSocketOptions().setIpV6(false)); DatagramSocket client = vertx.createDatagramSocket(new DatagramSocketOptions().setIpV6(false)); diff --git a/src/test/java/io/floci/aws/core/common/dns/DnsTestQuery.java b/src/test/java/io/floci/aws/core/common/dns/DnsTestQuery.java index 2615f45019..9548ea651b 100644 --- a/src/test/java/io/floci/aws/core/common/dns/DnsTestQuery.java +++ b/src/test/java/io/floci/aws/core/common/dns/DnsTestQuery.java @@ -1,8 +1,15 @@ package io.floci.aws.core.common.dns; +import com.github.dockerjava.api.DockerClient; +import io.floci.aws.core.common.docker.ContainerExec; + import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; +import java.util.HexFormat; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; final class DnsTestQuery { @@ -20,4 +27,20 @@ final class DnsTestQuery { query.put((byte) 0).putShort((short) type).putShort((short) 1); return Arrays.copyOf(query.array(), query.position()); } + + static byte[] queryGuest(DockerClient docker, String containerId, String name, String address, int port) + throws Exception { + byte[] packet = DnsTestQuery.query(name, 1, 0x1234); + ContainerExec.Result result = ContainerExec.run(docker, containerId, + new String[] {"python", "-c", + "import socket,sys; s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM); s.settimeout(3); " + + "s.sendto(bytes.fromhex(sys.argv[1]),(sys.argv[2],int(sys.argv[3]))); " + + "print(s.recvfrom(4096)[0].hex()); s.close()", + HexFormat.of().formatHex(packet), address, Integer.toString(port)}, 10); + assertEquals(0, result.exitCode(), result.summary()); + byte[] response = HexFormat.of().parseHex(result.stdout().replaceAll("\\s", "")); + assertTrue(response.length >= 12, "Guest must receive an actual DNS packet: " + result.summary()); + assertEquals(0x1234, ByteBuffer.wrap(response).getShort(0) & 65535); + return response; + } } diff --git a/src/test/java/io/floci/aws/core/common/dns/Ec2PrivateDnsGuestDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/core/common/dns/Ec2PrivateDnsGuestDockerNightlyIntegrationTest.java new file mode 100644 index 0000000000..9809a9c8aa --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/dns/Ec2PrivateDnsGuestDockerNightlyIntegrationTest.java @@ -0,0 +1,194 @@ +package io.floci.aws.core.common.dns; + +import com.github.dockerjava.api.DockerClient; +import io.floci.aws.core.common.docker.DockerBridgeAddress; +import io.floci.aws.services.cloudmap.CloudMapService; +import io.floci.aws.services.ec2.AmiImageResolver; +import io.floci.aws.services.ec2.Ec2MetadataServer; +import io.floci.aws.services.ec2.Ec2Service; +import io.floci.aws.services.ec2.ResolvedAmiImage; +import io.floci.aws.services.ec2.model.Instance; +import io.floci.aws.services.route53.Route53Service; +import io.floci.aws.services.route53.model.ResourceRecord; +import io.floci.aws.services.route53.model.ResourceRecordSet; +import io.floci.aws.services.route53.model.VpcAssociation; +import io.floci.aws.testing.DockerAvailability; +import io.floci.aws.testing.TestImages; +import io.quarkus.test.InjectMock; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import io.vertx.core.Vertx; +import io.vertx.core.datagram.DatagramSocket; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +import java.nio.ByteBuffer; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +@QuarkusTest +@TestProfile(Ec2PrivateDnsGuestDockerNightlyIntegrationTest.GuestProfile.class) +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +class Ec2PrivateDnsGuestDockerNightlyIntegrationTest { + + private static final String REGION = "us-east-1"; + + public static final class GuestProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.ec2.mock", "false", + "floci.network.security-group-enforcement.enabled", "false", + "floci.services.ec2.vpc-networks.enabled", "false", + "floci.docker.resource-namespace", "ec2-private-dns-guest-it"); + } + } + + @Inject + Ec2Service ec2; + @Inject + Ec2MetadataServer metadata; + @Inject + Route53Service route53; + @Inject + CloudMapService cloudMap; + @Inject + DockerClient docker; + @Inject + EmbeddedDnsServer dns; + @Inject + DockerBridgeAddress bridge; + @Inject + Vertx vertx; + @InjectMock + AmiImageResolver images; + + @Test + void guestDnsIsVpcScopedAndFollowsStopRestartAndTermination() throws Exception { + assumeTrue(DockerAvailability.isAvailable(), "Docker is required"); + String address = bridge.resolve().orElse(null); + assumeTrue(address != null, "A local Docker bridge is required"); + when(images.resolveImage(anyString())).thenReturn(ResolvedAmiImage.minimal(TestImages.PYTHON_ALPINE)); + String suffix = UUID.randomUUID().toString().substring(0, 8); + String name = "api.ec2-guest-" + suffix + ".example"; + String discoveryName = "api.ec2-discovery-" + suffix + ".example"; + List vpcs = new ArrayList<>(); + List subnets = new ArrayList<>(); + List instances = new ArrayList<>(); + String zone = null; + String namespace = null; + String discoveryService = null; + ResourceRecordSet record = new ResourceRecordSet(); + record.setName(name); + record.setType("A"); + record.setTtl(60L); + record.setRecords(List.of(new ResourceRecord("10.75.1.7"))); + DatagramSocket socket = dns.bind(vertx, address, 0, false).toCompletionStage() + .toCompletableFuture().get(10, TimeUnit.SECONDS); + try { + for (int octet : List.of(75, 76)) { + String vpc = ec2.createVpc(REGION, "10." + octet + ".0.0/16", false).getVpcId(); + vpcs.add(vpc); + subnets.add(ec2.createSubnet(REGION, vpc, "10." + octet + ".1.0/24", REGION + "a").getSubnetId()); + } + zone = route53.createHostedZone("ec2-guest-" + suffix + ".example", suffix, null, + new VpcAssociation(vpcs.getFirst(), REGION)).zone().getId(); + route53.changeResourceRecordSets(zone, List.of(Map.of("action", "CREATE", "rrs", record)), null); + namespace = cloudMap.createPrivateDnsNamespace("ec2-discovery-" + suffix + ".example", + vpcs.getFirst(), null, null, Map.of(), REGION).getTargets().get("NAMESPACE"); + discoveryService = cloudMap.createService("api", namespace, null, null, + "{\"DnsRecords\":[{\"Type\":\"A\",\"TTL\":15}]}", + null, null, null, Map.of(), REGION).getId(); + cloudMap.registerInstance(discoveryService, "guest-target", null, + Map.of("AWS_INSTANCE_IPV4", "10.75.1.7"), REGION); + for (String subnet : subnets) { + Instance instance = ec2.runInstances(REGION, "ami-alpine", "t3.micro", 1, 1, + null, List.of(), subnet, null, List.of(), null, null).getInstances().getFirst(); + instances.add(instance); + ec2.awaitContainerLaunch(instance); + assertEquals("running", instance.getState().getName()); + } + for (String hostname : List.of(name, discoveryName)) { + assertAnswer(instances.getFirst(), hostname, address, socket.localAddress().port()); + byte[] denied = query(instances.getLast(), hostname, address, socket.localAddress().port()); + assertEquals(0, ByteBuffer.wrap(denied).getShort(6), "Unrelated VPC must not receive " + hostname); + } + Instance instance = instances.getFirst(); + List transportAddresses = transportAddresses(instance); + assertTrue(transportAddresses.stream().anyMatch(ip -> metadata.vpcForClient(ip).isPresent())); + ec2.stopInstances(REGION, List.of(instance.getInstanceId())); + await().atMost(Duration.ofSeconds(40)).until(() -> "stopped".equals(instance.getState().getName())); + assertFalse(docker.inspectContainerCmd(instance.getDockerContainerId()).exec().getState().getRunning()); + assertTrue(transportAddresses.stream().allMatch(ip -> metadata.vpcForClient(ip).isEmpty()), + "Confirmed stop must revoke the guest transport origin"); + ec2.startInstances(REGION, List.of(instance.getInstanceId())); + ec2.awaitContainerLaunch(instance); + for (String hostname : List.of(name, discoveryName)) { + assertAnswer(instance, hostname, address, socket.localAddress().port()); + } + List restartedAddresses = transportAddresses(instance); + terminateAndAwait(instance); + assertTrue(restartedAddresses.stream().allMatch(ip -> metadata.vpcForClient(ip).isEmpty()), + "Confirmed termination must revoke the restarted guest origin"); + } finally { + for (Instance instance : instances.reversed()) { + terminateAndAwait(instance); + } + if (zone != null) { + route53.changeResourceRecordSets(zone, List.of(Map.of("action", "DELETE", "rrs", record)), null); + route53.deleteHostedZone(zone); + } + if (discoveryService != null) { + cloudMap.deregisterInstance(discoveryService, "guest-target", REGION); + cloudMap.deleteService(discoveryService); + } + if (namespace != null) { + cloudMap.deleteNamespace(namespace, REGION); + } + for (String subnet : subnets.reversed()) { + ec2.deleteSubnet(REGION, subnet); + } + for (String vpc : vpcs.reversed()) { + ec2.deleteVpc(REGION, vpc); + } + socket.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS); + } + } + + List transportAddresses(Instance instance) { + return docker.inspectContainerCmd(instance.getDockerContainerId()).exec() + .getNetworkSettings().getNetworks().values().stream() + .map(network -> network.getIpAddress()).filter(ip -> ip != null && !ip.isBlank()).toList(); + } + + private void terminateAndAwait(Instance instance) { + ec2.terminateInstances(REGION, List.of(instance.getInstanceId())); + await().atMost(Duration.ofSeconds(30)).until(() -> "terminated".equals(instance.getState().getName())); + } + + private void assertAnswer(Instance instance, String name, String address, int port) throws Exception { + byte[] response = query(instance, name, address, port); + assertEquals(0, ByteBuffer.wrap(response).getShort(2) & 15); + assertEquals(1, ByteBuffer.wrap(response).getShort(6)); + assertArrayEquals(new byte[]{10, 75, 1, 7}, Arrays.copyOfRange(response, response.length - 4, response.length)); + } + + private byte[] query(Instance instance, String name, String address, int port) throws Exception { + return DnsTestQuery.queryGuest(docker, instance.getDockerContainerId(), name, address, port); + } +} diff --git a/src/test/java/io/floci/aws/core/common/dns/Ec2ProtectedPrivateDnsGuestDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/core/common/dns/Ec2ProtectedPrivateDnsGuestDockerNightlyIntegrationTest.java new file mode 100644 index 0000000000..60f474fa74 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/dns/Ec2ProtectedPrivateDnsGuestDockerNightlyIntegrationTest.java @@ -0,0 +1,41 @@ +package io.floci.aws.core.common.dns; + +import io.floci.aws.services.ec2.model.Instance; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +@TestProfile(Ec2ProtectedPrivateDnsGuestDockerNightlyIntegrationTest.ProtectedGuestProfile.class) +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +class Ec2ProtectedPrivateDnsGuestDockerNightlyIntegrationTest extends Ec2PrivateDnsGuestDockerNightlyIntegrationTest { + + public static final class ProtectedGuestProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.ec2.mock", "false", + "floci.network.security-group-enforcement.enabled", "true", + "floci.services.ec2.vpc-networks.enabled", "false", + "floci.docker.resource-namespace", "ec2-protected-private-dns-guest-it"); + } + } + + @Override + List transportAddresses(Instance instance) { + String mode = docker.inspectContainerCmd(instance.getDockerContainerId()).exec() + .getHostConfig().getNetworkMode(); + assertTrue(mode.startsWith("container:"), "Guest must use its protected network namespace"); + List addresses = docker.inspectContainerCmd(mode.substring("container:".length())).exec() + .getNetworkSettings().getNetworks().values().stream() + .map(network -> network.getIpAddress()).filter(ip -> ip != null && !ip.isBlank()).toList(); + assertFalse(addresses.isEmpty(), "Protected helper must own a transport address"); + return addresses; + } +} diff --git a/src/test/java/io/floci/aws/core/common/dns/EcsPrivateDnsGuestDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/core/common/dns/EcsPrivateDnsGuestDockerNightlyIntegrationTest.java new file mode 100644 index 0000000000..9f06c84b22 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/dns/EcsPrivateDnsGuestDockerNightlyIntegrationTest.java @@ -0,0 +1,276 @@ +package io.floci.aws.core.common.dns; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.exception.ConflictException; +import com.github.dockerjava.api.exception.NotFoundException; +import io.floci.aws.core.common.docker.ContainerExec; +import io.floci.aws.core.common.docker.DockerBridgeAddress; +import io.floci.aws.services.cloudmap.CloudMapService; +import io.floci.aws.services.ec2.Ec2Service; +import io.floci.aws.services.ecs.EcsService; +import io.floci.aws.services.ecs.container.EcsContainerManager; +import io.floci.aws.services.ecs.model.AwsVpcConfiguration; +import io.floci.aws.services.ecs.model.ContainerDefinition; +import io.floci.aws.services.ecs.model.EcsTask; +import io.floci.aws.services.ecs.model.LaunchType; +import io.floci.aws.services.ecs.model.NetworkConfiguration; +import io.floci.aws.services.ecs.model.NetworkMode; +import io.floci.aws.services.ecs.model.TaskDefinition; +import io.floci.aws.services.route53.Route53Service; +import io.floci.aws.services.route53.model.ResourceRecord; +import io.floci.aws.services.route53.model.ResourceRecordSet; +import io.floci.aws.services.route53.model.VpcAssociation; +import io.floci.aws.testing.DockerAvailability; +import io.floci.aws.testing.TestImages; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import io.vertx.core.Vertx; +import io.vertx.core.datagram.DatagramSocket; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +import java.nio.ByteBuffer; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static io.floci.aws.testing.EcsTaskWaits.awaitLastStatus; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +@QuarkusTest +@TestProfile(EcsPrivateDnsGuestDockerNightlyIntegrationTest.GuestProfile.class) +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +class EcsPrivateDnsGuestDockerNightlyIntegrationTest { + + private static final String REGION = "us-east-1"; + + public static final class GuestProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.ecs.mock", "false", + "floci.network.security-group-enforcement.enabled", "false", + "floci.services.ec2.vpc-networks.enabled", "false", + "floci.docker.resource-namespace", "ecs-private-dns-guest-it"); + } + } + + @Inject + EcsService ecs; + @Inject + Ec2Service ec2; + @Inject + Route53Service route53; + @Inject + CloudMapService cloudMap; + @Inject + DockerClient docker; + @Inject + EcsContainerManager containers; + @Inject + EmbeddedDnsServer dns; + @Inject + DockerBridgeAddress bridge; + @Inject + Vertx vertx; + + @Test + void managedGuestQueriesAreScopedToTheirVpcAndStopRevokesTheirOrigin() throws Exception { + assumeTrue(DockerAvailability.isAvailable(), "Docker is required"); + String address = bridge.resolve().orElse(null); + assumeTrue(address != null, "A local Docker bridge is required"); + String suffix = UUID.randomUUID().toString().substring(0, 8); + String cluster = "dns-guest-" + suffix; + String name = "api.guest-" + suffix + ".example"; + List vpcs = new ArrayList<>(); + List subnets = new ArrayList<>(); + List tasks = new ArrayList<>(); + String definition = null; + String zone = null; + String namespace = null; + String discoveryService = null; + String discoveryName = "api.discovery-" + suffix + ".example"; + ResourceRecordSet record = new ResourceRecordSet(); + record.setName(name); + record.setType("A"); + record.setTtl(60L); + record.setRecords(List.of(new ResourceRecord("10.73.1.7"))); + DatagramSocket socket = dns.bind(vertx, address, 0, false).toCompletionStage() + .toCompletableFuture().get(10, TimeUnit.SECONDS); + ecs.createCluster(cluster, REGION); + try { + for (int octet : List.of(73, 74)) { + String vpc = ec2.createVpc(REGION, "10." + octet + ".0.0/16", false).getVpcId(); + vpcs.add(vpc); + subnets.add(ec2.createSubnet(REGION, vpc, "10." + octet + ".1.0/24", REGION + "a") + .getSubnetId()); + } + zone = route53.createHostedZone("guest-" + suffix + ".example", suffix, null, + new VpcAssociation(vpcs.getFirst(), REGION)).zone().getId(); + route53.changeResourceRecordSets(zone, List.of(Map.of("action", "CREATE", "rrs", record)), null); + namespace = cloudMap.createPrivateDnsNamespace("discovery-" + suffix + ".example", + vpcs.getFirst(), null, null, Map.of(), REGION).getTargets().get("NAMESPACE"); + discoveryService = cloudMap.createService("api", namespace, null, null, + "{\"DnsRecords\":[{\"Type\":\"A\",\"TTL\":15}]}", null, null, null, Map.of(), REGION).getId(); + cloudMap.registerInstance(discoveryService, "guest-target", null, + Map.of("AWS_INSTANCE_IPV4", "10.73.1.7"), REGION); + ContainerDefinition app = new ContainerDefinition(); + app.setName("dns-client"); + app.setImage(TestImages.PYTHON_ALPINE); + app.setCommand(List.of("python", "-c", """ + import os, signal, sys + os.mkfifo('/tmp/dns-release') + def stopping(signum, frame): + open('/tmp/dns-stopping', 'w').close() + with open('/tmp/dns-release') as release: + release.read() + sys.exit(0) + signal.signal(signal.SIGTERM, stopping) + open('/tmp/dns-ready', 'w').close() + while True: + signal.pause() + """)); + app.setStopTimeout(30); + TaskDefinition registered = ecs.registerTaskDefinition("dns-guest-" + suffix, List.of(app), + NetworkMode.awsvpc, null, null, null, null, null, REGION); + definition = registered.getTaskDefinitionArn(); + for (String subnet : subnets) { + AwsVpcConfiguration attachment = new AwsVpcConfiguration(); + attachment.setSubnets(List.of(subnet)); + NetworkConfiguration network = new NetworkConfiguration(); + network.setAwsvpcConfiguration(attachment); + EcsTask task = ecs.runTask(cluster, definition, 1, LaunchType.FARGATE, + null, null, List.of(), network, REGION).getFirst(); + tasks.add(task); + EcsTask running = awaitLastStatus( + () -> ecs.describeTasks(cluster, List.of(task.getTaskArn()), REGION).getFirst(), + EcsTask::getLastStatus, Duration.ofMinutes(2), "RUNNING", "STOPPED"); + assertEquals("RUNNING", running.getLastStatus(), running.getStoppedReason()); + tasks.set(tasks.size() - 1, running); + awaitFile(running, "/tmp/dns-ready"); + } + byte[] allowed = query(tasks.getFirst(), name, address, socket.localAddress().port()); + assertEquals(0, ByteBuffer.wrap(allowed).getShort(2) & 15); + assertEquals(1, ByteBuffer.wrap(allowed).getShort(6)); + assertArrayEquals(new byte[]{10, 73, 1, 7}, + Arrays.copyOfRange(allowed, allowed.length - 4, allowed.length)); + byte[] denied = query(tasks.getLast(), name, address, socket.localAddress().port()); + assertEquals(0, ByteBuffer.wrap(denied).getShort(6), + "A real guest from an unrelated VPC must not receive the private answer"); + byte[] discoveryAllowed = query(tasks.getFirst(), discoveryName, address, socket.localAddress().port()); + assertEquals(0, ByteBuffer.wrap(discoveryAllowed).getShort(2) & 15); + assertEquals(1, ByteBuffer.wrap(discoveryAllowed).getShort(6)); + assertArrayEquals(new byte[]{10, 73, 1, 7}, + Arrays.copyOfRange(discoveryAllowed, discoveryAllowed.length - 4, discoveryAllowed.length)); + byte[] discoveryDenied = query(tasks.getLast(), discoveryName, address, socket.localAddress().port()); + assertEquals(0, ByteBuffer.wrap(discoveryDenied).getShort(6), + "An unrelated guest must not receive a private CloudMap answer"); + String dockerId = tasks.getFirst().getContainers().getFirst().getDockerId(); + InspectContainerResponse guest = docker.inspectContainerCmd(dockerId).exec(); + String networkMode = guest.getHostConfig().getNetworkMode(); + assertEquals(usesSharedNamespace(), networkMode.startsWith("container:"), + "The guest must use the network mode selected by this fixture"); + String transportId = usesSharedNamespace() ? networkMode.substring("container:".length()) : dockerId; + List transportAddresses = docker.inspectContainerCmd(transportId).exec() + .getNetworkSettings().getNetworks().values().stream() + .map(network -> network.getIpAddress()).filter(ip -> ip != null && !ip.isBlank()).toList(); + assertTrue(transportAddresses.stream().anyMatch(ip -> containers.vpcForClient(ip).isPresent())); + stopWithGuestQueryDuringGrace(cluster, tasks.getFirst(), List.of(name, discoveryName), + address, socket.localAddress().port()); + assertTrue(transportAddresses.stream().allMatch(ip -> containers.vpcForClient(ip).isEmpty()), + "Confirmed guest stop must revoke its actual transport addresses"); + } finally { + for (EcsTask task : tasks.reversed()) { + String id = task.getContainers().getFirst().getDockerId(); + if (id != null) { + try { + docker.killContainerCmd(id).exec(); + } catch (NotFoundException | ConflictException ignored) { + // The tested stop may already have removed or stopped this container. + } + } + ecs.stopTask(cluster, task.getTaskArn(), "DNS guest cleanup", REGION); + } + if (definition != null) { + ecs.deregisterTaskDefinition(definition, REGION); + } + ecs.deleteCluster(cluster, REGION); + if (zone != null) { + route53.changeResourceRecordSets(zone, List.of(Map.of("action", "DELETE", "rrs", record)), null); + route53.deleteHostedZone(zone); + } + if (discoveryService != null) { + cloudMap.deregisterInstance(discoveryService, "guest-target", REGION); + cloudMap.deleteService(discoveryService); + } + if (namespace != null) { + cloudMap.deleteNamespace(namespace, REGION); + } + for (String subnet : subnets.reversed()) { + ec2.deleteSubnet(REGION, subnet); + } + for (String vpc : vpcs.reversed()) { + ec2.deleteVpc(REGION, vpc); + } + socket.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS); + } + } + + boolean usesSharedNamespace() { + return false; + } + + private void awaitFile(EcsTask task, String file) { + await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> { + ContainerExec.Result result = ContainerExec.run(docker, + task.getContainers().getFirst().getDockerId(), + new String[] {"python", "-c", "import os,sys; sys.exit(not os.path.exists(sys.argv[1]))", file}, 5); + assertEquals(0, result.exitCode(), result.summary()); + }); + } + + private void stopWithGuestQueryDuringGrace(String cluster, EcsTask task, List names, + String address, int port) throws Exception { + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future stopped = executor.submit(() -> ecs.stopTask(cluster, task.getTaskArn(), "DNS grace test", REGION)); + try { + awaitFile(task, "/tmp/dns-stopping"); + try { + for (String name : names) { + byte[] duringGrace = query(task, name, address, port); + assertEquals(1, ByteBuffer.wrap(duringGrace).getShort(6), + "A real guest must retain private DNS during grace: " + name); + assertArrayEquals(new byte[]{10, 73, 1, 7}, + Arrays.copyOfRange(duringGrace, duringGrace.length - 4, duringGrace.length)); + } + } finally { + ContainerExec.Result released = ContainerExec.run(docker, + task.getContainers().getFirst().getDockerId(), + new String[] {"python", "-c", "with open('/tmp/dns-release','w') as release: release.write('done')"}, + 5); + assertEquals(0, released.exitCode(), released.summary()); + } + stopped.get(10, TimeUnit.SECONDS); + } finally { + executor.shutdownNow(); + assertTrue(executor.awaitTermination(40, TimeUnit.SECONDS), "Owned stop worker must finish"); + } + } + + private byte[] query(EcsTask task, String name, String address, int port) throws Exception { + return DnsTestQuery.queryGuest(docker, task.getContainers().getFirst().getDockerId(), name, address, port); + } +} diff --git a/src/test/java/io/floci/aws/core/common/dns/EcsProtectedPrivateDnsGuestDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/core/common/dns/EcsProtectedPrivateDnsGuestDockerNightlyIntegrationTest.java new file mode 100644 index 0000000000..0698edb431 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/dns/EcsProtectedPrivateDnsGuestDockerNightlyIntegrationTest.java @@ -0,0 +1,30 @@ +package io.floci.aws.core.common.dns; + +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +import java.util.Map; + +@QuarkusTest +@TestProfile(EcsProtectedPrivateDnsGuestDockerNightlyIntegrationTest.ProtectedGuestProfile.class) +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +class EcsProtectedPrivateDnsGuestDockerNightlyIntegrationTest extends EcsPrivateDnsGuestDockerNightlyIntegrationTest { + + public static final class ProtectedGuestProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.ecs.mock", "false", + "floci.services.ecs.shared-task-network", "true", + "floci.network.security-group-enforcement.enabled", "true", + "floci.services.ec2.vpc-networks.enabled", "false", + "floci.docker.resource-namespace", "ecs-protected-private-dns-guest-it"); + } + } + + @Override + boolean usesSharedNamespace() { + return true; + } +} diff --git a/src/test/java/io/floci/aws/core/common/dns/EcsSharedPrivateDnsGuestDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/core/common/dns/EcsSharedPrivateDnsGuestDockerNightlyIntegrationTest.java new file mode 100644 index 0000000000..ac3e8aed16 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/dns/EcsSharedPrivateDnsGuestDockerNightlyIntegrationTest.java @@ -0,0 +1,30 @@ +package io.floci.aws.core.common.dns; + +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +import java.util.Map; + +@QuarkusTest +@TestProfile(EcsSharedPrivateDnsGuestDockerNightlyIntegrationTest.SharedGuestProfile.class) +@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true") +class EcsSharedPrivateDnsGuestDockerNightlyIntegrationTest extends EcsPrivateDnsGuestDockerNightlyIntegrationTest { + + public static final class SharedGuestProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.ecs.mock", "false", + "floci.services.ecs.shared-task-network", "true", + "floci.network.security-group-enforcement.enabled", "false", + "floci.services.ec2.vpc-networks.enabled", "false", + "floci.docker.resource-namespace", "ecs-shared-private-dns-guest-it"); + } + } + + @Override + boolean usesSharedNamespace() { + return true; + } +} diff --git a/src/test/java/io/floci/aws/core/common/dns/EmbeddedDnsServerTest.java b/src/test/java/io/floci/aws/core/common/dns/EmbeddedDnsServerTest.java index e5c69455bc..fc77b7d704 100644 --- a/src/test/java/io/floci/aws/core/common/dns/EmbeddedDnsServerTest.java +++ b/src/test/java/io/floci/aws/core/common/dns/EmbeddedDnsServerTest.java @@ -314,6 +314,33 @@ class EmbeddedDnsServerTest { dns.planQuery("db.corp.internal", CLIENT, MY_IP, 1)); } + @Test + void planQueryDoesNotChooseBetweenConflictingRuntimeOrigins() { + for (DnsClientVpcSource.ClientVpc other : List.of( + new DnsClientVpcSource.ClientVpc("111111111111", REGION, "vpc-a"), + new DnsClientVpcSource.ClientVpc(ACCOUNT, "us-west-2", "vpc-a"), + new DnsClientVpcSource.ClientVpc(ACCOUNT, REGION, "vpc-other"))) { + DnsClientVpcSource conflicting = address -> Optional.of(other); + for (List sources : List.of(List.of(clientVpc("vpc-a"), conflicting), + List.of(conflicting, clientVpc("vpc-a")))) { + EmbeddedDnsServer server = new EmbeddedDnsServer(List.of(), + List.of(source("db.corp.internal", List.of("192.0.2.17"))), + List.of(rules("vpc-a", forward("corp.internal", "10.1.0.53"))), sources); + assertEquals(EmbeddedDnsServer.QueryPlan.answering(DnsAnswer.refused()), + server.planQuery("db.corp.internal", CLIENT, MY_IP, 1)); + } + } + } + + @Test + void planQueryAcceptsMatchingRuntimeOrigins() { + EmbeddedDnsServer server = new EmbeddedDnsServer(List.of(), List.of(), + List.of(rules("vpc-a", forward("corp.internal", "10.1.0.53"))), + List.of(clientVpc("vpc-a"), clientVpc("vpc-a"))); + assertEquals(List.of(new DnsForwardingRule.Target("10.1.0.53", 53)), + server.planQuery("db.corp.internal", CLIENT, MY_IP, 1).ruleTargets()); + } + @Test void planQuery_appliesNoRuleWhenTheQueryOriginIsIncomplete() { DnsForwardingRuleSource anyOrigin = (accountId, region, vpcId) -> diff --git a/src/test/java/io/floci/aws/core/common/dns/PrivateHostedZoneVpcScopeIntegrationTest.java b/src/test/java/io/floci/aws/core/common/dns/PrivateHostedZoneVpcScopeIntegrationTest.java new file mode 100644 index 0000000000..8540d80f20 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/dns/PrivateHostedZoneVpcScopeIntegrationTest.java @@ -0,0 +1,283 @@ +package io.floci.aws.core.common.dns; + +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.services.cloudmap.CloudMapDnsRecordSource; +import io.floci.aws.services.cloudmap.CloudMapService; +import io.floci.aws.services.cloudmap.model.Service; +import io.floci.aws.services.route53.Route53DnsRecordSource; +import io.floci.aws.services.route53.Route53Service; +import io.floci.aws.services.route53.model.ResourceRecord; +import io.floci.aws.services.route53.model.ResourceRecordSet; +import io.floci.aws.services.route53.model.VpcAssociation; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.ec2.Ec2Client; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class PrivateHostedZoneVpcScopeIntegrationTest { + + @Inject + Route53Service route53; + + @Inject + Route53DnsRecordSource records; + + @Inject + EmulatorConfig config; + + @Inject + CloudMapService cloudMap; + + @Inject + CloudMapDnsRecordSource cloudMapRecords; + + @TestHTTPResource + URI endpoint; + + private final List zones = new ArrayList<>(); + private final List namespaces = new ArrayList<>(); + private final List services = new ArrayList<>(); + private Ec2Client sdk; + private String firstVpc; + private String secondVpc; + + @BeforeEach + void createVpcIdentities() { + sdk = Ec2Client.builder().endpointOverride(endpoint).region(Region.US_EAST_1) + .httpClientBuilder(UrlConnectionHttpClient.builder()) + .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))) + .build(); + firstVpc = sdk.createVpc(request -> request.cidrBlock("10.73.0.0/16")).vpc().vpcId(); + secondVpc = sdk.createVpc(request -> request.cidrBlock("10.74.0.0/16")).vpc().vpcId(); + } + + @AfterEach + void deleteOwnedResources() { + try { + for (String service : services.reversed()) { + cloudMap.deregisterInstance(service, "task-1", "us-east-1"); + cloudMap.deleteService(service); + } + for (String namespace : namespaces.reversed()) { + cloudMap.deleteNamespace(namespace, "us-east-1"); + } + for (String id : zones.reversed()) { + List> deletes = route53.listResourceRecordSets(id, null, null, 100).stream() + .filter(record -> !"NS".equals(record.getType()) && !"SOA".equals(record.getType())) + .map(record -> Map.of("action", "DELETE", "rrs", record)).toList(); + if (!deletes.isEmpty()) { + route53.changeResourceRecordSets(id, deletes, null); + } + route53.deleteHostedZone(id); + } + if (firstVpc != null) { + sdk.deleteVpc(request -> request.vpcId(firstVpc)); + } + if (secondVpc != null) { + sdk.deleteVpc(request -> request.vpcId(secondVpc)); + } + } finally { + if (sdk != null) { + sdk.close(); + } + } + } + + @Test + void associatedVpcGetsPrivateAnswerAndOtherVpcGetsPublicAnswer() { + String name = uniqueName(); + addAddress(zone(name, firstVpc), "api." + name, "10.73.1.7"); + addAddress(zone(name, null), "api." + name, "203.0.113.7"); + + assertEquals(List.of("10.73.1.7"), answer("api." + name, "192.0.2.10").orElseThrow().addresses()); + assertEquals(List.of("203.0.113.7"), answer("api." + name, "192.0.2.20").orElseThrow().addresses()); + } + + @Test + void unknownCallerRetainsPrivateAnswerAheadOfPublicRecords() { + String name = uniqueName(); + addAddress(zone(name, firstVpc), "api." + name, "10.73.1.7"); + addAddress(zone(name, null), "api." + name, "203.0.113.7"); + + assertEquals(List.of("10.73.1.7"), answer("api." + name, null).orElseThrow().addresses()); + } + + @Test + void unassociatedPrivateZoneDoesNotClaimTheName() { + String name = uniqueName(); + addAddress(zone(name, firstVpc), "api." + name, "10.73.1.7"); + + assertTrue(answer("api." + name, "192.0.2.20").isEmpty(), + "An unassociated private zone must leave the name to public resolution"); + } + + @Test + void moreSpecificZoneInAnotherVpcDoesNotHideTheAssociatedParent() { + String parent = uniqueName(); + String child = "child." + parent; + addAddress(zone(parent, firstVpc), "api." + child, "10.73.1.7"); + addAddress(zone(child, secondVpc), "api." + child, "10.74.1.7"); + + assertEquals(List.of("10.73.1.7"), answer("api." + child, "192.0.2.10").orElseThrow().addresses()); + assertEquals(List.of("10.74.1.7"), answer("api." + child, "192.0.2.20").orElseThrow().addresses()); + } + + @Test + void associatedPrivateNegativeAnswerDoesNotFallBackToPublicRecords() { + String name = uniqueName(); + zone(name, firstVpc); + addAddress(zone(name, null), "api." + name, "203.0.113.7"); + + assertEquals(3, answer("api." + name, "192.0.2.10").orElseThrow().responseCode()); + } + + @Test + void associationAndDisassociationChangeSubsequentAnswers() { + String name = uniqueName(); + String privateZone = zone(name, firstVpc); + addAddress(privateZone, "api." + name, "10.73.1.7"); + addAddress(zone(name, null), "api." + name, "203.0.113.7"); + assertEquals(List.of("203.0.113.7"), answer("api." + name, "192.0.2.20").orElseThrow().addresses()); + + route53.associateVpcWithHostedZone(privateZone, new VpcAssociation(secondVpc, "us-east-1"), null); + assertEquals(List.of("10.73.1.7"), answer("api." + name, "192.0.2.20").orElseThrow().addresses()); + + route53.disassociateVpcFromHostedZone(privateZone, new VpcAssociation(secondVpc, "us-east-1"), null); + assertEquals(List.of("203.0.113.7"), answer("api." + name, "192.0.2.20").orElseThrow().addresses()); + } + + @Test + void vpcIdWithoutMatchingAccountAndRegionDoesNotGrantVisibility() { + String name = uniqueName(); + addAddress(zone(name, firstVpc), "api." + name, "10.73.1.7"); + for (DnsClientVpcSource.ClientVpc origin : List.of( + new DnsClientVpcSource.ClientVpc("222222222222", "us-east-1", firstVpc), + new DnsClientVpcSource.ClientVpc(config.defaultAccountId(), "us-west-2", firstVpc))) { + EmbeddedDnsServer server = new EmbeddedDnsServer(List.of(), List.of(records), + List.of(), List.of(address -> Optional.of(origin))); + assertTrue(server.planQuery("api." + name, "192.0.2.10", "127.0.0.1", 1).answer().isEmpty()); + } + } + + @Test + void cloudMapPrivateAnswersFollowBackingZoneAssociationsInEitherSourceOrder() { + String name = uniqueName(); + String namespace = cloudMapNamespace(name, firstVpc); + register(namespace, "api", "10.73.1.7"); + for (List sources : sourceOrders()) { + assertEquals(List.of("10.73.1.7"), + answer("api." + name, "192.0.2.10", sources).orElseThrow().addresses()); + assertTrue(answer("api." + name, "192.0.2.20", sources).isEmpty()); + assertEquals(List.of("10.73.1.7"), answer("api." + name, null, sources).map(DnsAnswer::addresses).orElse(List.of())); + } + + String backingZone = cloudMap.getNamespace(namespace).getHostedZoneId(); + route53.associateVpcWithHostedZone(backingZone, new VpcAssociation(secondVpc, "us-east-1"), null); + for (List sources : sourceOrders()) { + assertEquals(List.of("10.73.1.7"), + answer("api." + name, "192.0.2.20", sources).orElseThrow().addresses()); + } + route53.disassociateVpcFromHostedZone(backingZone, new VpcAssociation(secondVpc, "us-east-1"), null); + assertTrue(answer("api." + name, "192.0.2.20", List.of(cloudMapRecords)).isEmpty()); + } + + @Test + void associatedChildZoneNegativeAnswerCannotFallThroughToParentCloudMapNamespace() { + String parent = uniqueName(); + register(cloudMapNamespace(parent, firstVpc), "api.child", "10.73.1.7"); + zone("child." + parent, firstVpc); + + for (List sources : sourceOrders()) { + assertEquals(3, answer("api.child." + parent, "192.0.2.10", sources).orElseThrow().responseCode()); + } + } + + @Test + void associatedPrivateZoneNegativeAnswerCannotFallThroughToPublicCloudMapNamespace() { + String name = uniqueName(); + register(cloudMapNamespace(name, null), "api", "203.0.113.7"); + zone(name, firstVpc); + + for (List sources : sourceOrders()) { + assertEquals(3, answer("api." + name, "192.0.2.10", sources).orElseThrow().responseCode()); + } + assertEquals(List.of("203.0.113.7"), + answer("api." + name, "192.0.2.20", List.of(cloudMapRecords)).orElseThrow().addresses()); + } + + private List> sourceOrders() { + return List.of(List.of(records, cloudMapRecords), List.of(cloudMapRecords, records)); + } + + private String cloudMapNamespace(String name, String vpc) { + String id = (vpc == null + ? cloudMap.createPublicDnsNamespace(name, null, null, Map.of(), "us-east-1") + : cloudMap.createPrivateDnsNamespace(name, vpc, null, null, Map.of(), "us-east-1")) + .getTargets().get("NAMESPACE"); + namespaces.add(id); + return id; + } + + private void register(String namespace, String name, String address) { + Service service = cloudMap.createService(name, namespace, null, null, + "{\"DnsRecords\":[{\"Type\":\"A\",\"TTL\":60}]}", null, null, null, Map.of(), "us-east-1"); + services.add(service.getId()); + cloudMap.registerInstance(service.getId(), "task-1", null, + Map.of("AWS_INSTANCE_IPV4", address), "us-east-1"); + } + + private Optional answer(String name, String sourceAddress) { + return answer(name, sourceAddress, List.of(records)); + } + + private Optional answer(String name, String sourceAddress, List sources) { + DnsClientVpcSource clients = address -> switch (address) { + case "192.0.2.10" -> Optional.of(new DnsClientVpcSource.ClientVpc( + config.defaultAccountId(), "us-east-1", firstVpc)); + case "192.0.2.20" -> Optional.of(new DnsClientVpcSource.ClientVpc( + config.defaultAccountId(), "us-east-1", secondVpc)); + default -> Optional.empty(); + }; + EmbeddedDnsServer server = new EmbeddedDnsServer( + List.of(), sources, List.of(), List.of(clients)); + return server.planQuery(name, sourceAddress, "127.0.0.1", 1).answer(); + } + + private String zone(String name, String vpc) { + VpcAssociation association = vpc == null ? null : new VpcAssociation(vpc, "us-east-1"); + String id = route53.createHostedZone(name, UUID.randomUUID().toString(), null, association).zone().getId(); + zones.add(id); + return id; + } + + private void addAddress(String zone, String name, String address) { + ResourceRecordSet record = new ResourceRecordSet(); + record.setName(name); + record.setType("A"); + record.setTtl(60L); + record.setRecords(List.of(new ResourceRecord(address))); + route53.changeResourceRecordSets(zone, List.of(Map.of("action", "CREATE", "rrs", record)), null); + } + + private static String uniqueName() { + return "vpc-scope-" + UUID.randomUUID() + ".example"; + } +} diff --git a/src/test/java/io/floci/aws/core/common/dns/Route53DnsPacketIntegrationTest.java b/src/test/java/io/floci/aws/core/common/dns/Route53DnsPacketIntegrationTest.java index d6edf70a8d..978657f5b4 100644 --- a/src/test/java/io/floci/aws/core/common/dns/Route53DnsPacketIntegrationTest.java +++ b/src/test/java/io/floci/aws/core/common/dns/Route53DnsPacketIntegrationTest.java @@ -1,5 +1,8 @@ package io.floci.aws.core.common.dns; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.services.ec2.Ec2MetadataServer; +import io.floci.aws.services.ec2.model.Instance; import io.floci.aws.services.route53.Route53DnsRecordSource; import io.floci.aws.services.route53.Route53Service; import io.floci.aws.services.route53.model.AliasTarget; @@ -7,6 +10,7 @@ import io.floci.aws.services.route53.model.ResourceRecord; import io.floci.aws.services.route53.model.ResourceRecordSet; import io.floci.aws.services.route53.model.VpcAssociation; import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.ParallelLocks; import io.quarkus.test.junit.QuarkusTest; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; @@ -15,6 +19,7 @@ import io.vertx.core.datagram.DatagramSocketOptions; import jakarta.inject.Inject; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import software.amazon.awssdk.regions.Region; @@ -25,6 +30,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; +import java.util.Optional; +import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; @@ -43,9 +50,97 @@ class Route53DnsPacketIntegrationTest { Route53DnsRecordSource source; @Inject Vertx vertx; + @Inject + EmulatorConfig config; + + @Inject + Ec2MetadataServer metadata; + @Inject + jakarta.enterprise.inject.Instance origins; // CDI Instance and the EC2 model share a name. private final List zoneIds = new ArrayList<>(); + @Test + void conflictingRuntimeOriginsRefusePrivateRecordsAcrossTheWire() throws Exception { + String zone = uniqueName() + ".example"; + String id; + try (Route53Client client = AwsTestClients.create(Route53Client.builder(), "test", Region.US_EAST_1)) { + id = client.createHostedZone(request -> request.name(zone).callerReference(UUID.randomUUID().toString()) + .vpc(vpc -> vpc.vpcId("vpc-conflict").vpcRegion("us-east-1"))).hostedZone().id(); + zoneIds.add(id); + } + String name = "service." + zone; + change(id, "CREATE", record(name, "A", 17, "192.0.2.17")); + DnsClientVpcSource known = address -> Optional.of(new DnsClientVpcSource.ClientVpc( + config.defaultAccountId(), "us-east-1", "vpc-conflict")); + byte[] request = DnsTestQuery.query(name, 1, 0x1234); + for (DnsClientVpcSource.ClientVpc other : List.of( + new DnsClientVpcSource.ClientVpc("111111111111", "us-east-1", "vpc-conflict"), + new DnsClientVpcSource.ClientVpc(config.defaultAccountId(), "us-west-2", "vpc-conflict"), + new DnsClientVpcSource.ClientVpc(config.defaultAccountId(), "us-east-1", "vpc-other"))) { + DnsClientVpcSource conflicting = address -> Optional.of(other); + for (List providers : List.of(List.of(known, conflicting), List.of(conflicting, known))) { + ByteBuffer response = ByteBuffer.wrap(queryWithOrigins(request, providers)); + assertEquals(5, response.getShort(2) & 15); + assertEquals(0, response.getShort(6)); + } + } + assertRuntimeAddress(queryWithOrigins(request, List.of(known, known)), "192.0.2.17"); + assertRuntimeAddress(queryWithOrigins(request, List.of()), "192.0.2.17"); + } + + @Test + @ResourceLock(ParallelLocks.PORTS) + void ec2RuntimeOriginReconcilesPrivateDnsAccessAcrossTheWire() throws Exception { + String zone = uniqueName() + ".example"; + String id; + String publicId; + try (Route53Client client = AwsTestClients.create(Route53Client.builder(), "test", Region.US_EAST_1)) { + publicId = client.createHostedZone(request -> request.name(zone).callerReference(UUID.randomUUID().toString())) + .hostedZone().id(); + zoneIds.add(publicId); + id = client.createHostedZone(request -> request.name(zone).callerReference(UUID.randomUUID().toString()) + .vpc(vpc -> vpc.vpcId("vpc-ec2-dns").vpcRegion("us-east-1"))).hostedZone().id(); + zoneIds.add(id); + } + String name = "service." + zone; + change(id, "CREATE", record(name, "A", 17, "192.0.2.17")); + change(publicId, "CREATE", record(name, "A", 31, "203.0.113.17")); + Instance instance = new Instance(); + instance.setInstanceId("i-" + UUID.randomUUID()); + instance.setOwnerId(config.defaultAccountId()); + instance.setRegion("us-east-1"); + instance.setVpcId("vpc-ec2-dns"); + List runtimeOrigins = origins.stream().toList(); + byte[] request = DnsTestQuery.query(name, 1, 0x1234); + try { + assertRuntimeAddress(queryWithOrigins(request, runtimeOrigins), "192.0.2.17"); + metadata.registerContainer("127.0.0.1", instance.getInstanceId(), instance); + byte[] allowed = queryWithOrigins(request, runtimeOrigins); + assertPrivateHeader(allowed, 0, 1); + assertEquals(17, ByteBuffer.wrap(allowed).getInt(request.length + 6)); + assertArrayEquals(new DnsRecord.Address(1, "192.0.2.17").data(), + Arrays.copyOfRange(allowed, allowed.length - 4, allowed.length)); + metadata.reconcileContainerAddresses(Set.of("192.0.2.99"), instance); + assertRuntimeAddress(queryWithOrigins(request, runtimeOrigins), "192.0.2.17"); + metadata.reconcileContainerAddresses(Set.of("127.0.0.1"), instance); + assertPrivateHeader(queryWithOrigins(request, runtimeOrigins), 0, 1); + instance.setRegion("us-west-2"); + assertRuntimeAddress(queryWithOrigins(request, runtimeOrigins), "203.0.113.17"); + instance.setRegion("us-east-1"); + instance.setOwnerId("222222222222"); + assertRuntimeAddress(queryWithOrigins(request, runtimeOrigins), "203.0.113.17"); + instance.setOwnerId(config.defaultAccountId()); + instance.setVpcId("vpc-other"); + assertRuntimeAddress(queryWithOrigins(request, runtimeOrigins), "203.0.113.17"); + instance.setVpcId("vpc-ec2-dns"); + metadata.unregisterInstance(instance); + assertRuntimeAddress(queryWithOrigins(request, runtimeOrigins), "192.0.2.17"); + } finally { + metadata.unregisterInstance(instance); + } + } + @Test void privateSrvPreservesEveryFieldAndTtlAcrossTheWire() throws Exception { String zone = uniqueName() + ".example"; @@ -57,7 +152,7 @@ class Route53DnsPacketIntegrationTest { "20 0 8080 first." + zone + ".", "10 100 65535 second." + zone)); byte[] request = DnsTestQuery.query(name, 33, 0x1234); - byte[] response = query(request); + byte[] response = query(request, "vpc-srv"); assertPrivateHeader(response, 0, 2); ByteBuffer packet = ByteBuffer.wrap(response); packet.position(request.length); @@ -78,9 +173,9 @@ class Route53DnsPacketIntegrationTest { assertEquals(List.of("10 100 65535 second." + zone, "20 0 8080 first." + zone), values.stream().sorted().toList()); - assertPrivateHeader(query(DnsTestQuery.query(name, 1, 0x1234)), 0, 0); - assertPrivateHeader(query(DnsTestQuery.query("_tcp." + zone, 33, 0x1234)), 0, 0); - assertPrivateHeader(query(DnsTestQuery.query("absent." + zone, 33, 0x1234)), 3, 0); + assertPrivateHeader(query(DnsTestQuery.query(name, 1, 0x1234), "vpc-srv"), 0, 0); + assertPrivateHeader(query(DnsTestQuery.query("_tcp." + zone, 33, 0x1234), "vpc-srv"), 0, 0); + assertPrivateHeader(query(DnsTestQuery.query("absent." + zone, 33, 0x1234), "vpc-srv"), 3, 0); } @ParameterizedTest @@ -96,23 +191,23 @@ class Route53DnsPacketIntegrationTest { change(id, "CREATE", record("alias" + hop + "." + name, "CNAME", 30, target + ".")); } - assertEquals(3, ByteBuffer.wrap(query(DnsTestQuery.query(missing, type, 0x1234))).getShort(2) & 15); - byte[] response = query(DnsTestQuery.query("alias0." + name, type, 0x1234)); + assertEquals(3, ByteBuffer.wrap(query(DnsTestQuery.query(missing, type, 0x1234), "vpc-cname-negative")).getShort(2) & 15); + byte[] response = query(DnsTestQuery.query("alias0." + name, type, 0x1234), "vpc-cname-negative"); assertEquals(3, ByteBuffer.wrap(response).getShort(2) & 15, "A private CNAME must preserve its target's NXDOMAIN response"); assertEquals(0, ByteBuffer.wrap(response).getShort(6)); ResourceRecordSet text = record(missing, "TXT", 60, "\"present\""); change(id, "CREATE", text); - byte[] noData = query(DnsTestQuery.query("alias0." + name, type, 0x1234)); + byte[] noData = query(DnsTestQuery.query("alias0." + name, type, 0x1234), "vpc-cname-negative"); assertEquals(0, ByteBuffer.wrap(noData).getShort(2) & 15); assertEquals(0, ByteBuffer.wrap(noData).getShort(6)); change(id, "DELETE", text); - assertEquals(3, ByteBuffer.wrap(query(DnsTestQuery.query("alias0." + name, type, 0x1234))).getShort(2) & 15); + assertEquals(3, ByteBuffer.wrap(query(DnsTestQuery.query("alias0." + name, type, 0x1234), "vpc-cname-negative")).getShort(2) & 15); change(id, "CREATE", record(missing, "A", 600, "192.0.2.17")); byte[] request = DnsTestQuery.query("alias0." + name, 1, 0x1234); - byte[] restored = query(request); + byte[] restored = query(request, "vpc-cname-negative"); assertEquals(0, ByteBuffer.wrap(restored).getShort(2) & 15); assertEquals(1, ByteBuffer.wrap(restored).getShort(6)); assertEquals(30, ByteBuffer.wrap(restored).getInt(request.length + 6)); @@ -336,8 +431,10 @@ class Route53DnsPacketIntegrationTest { new VpcAssociation("vpc-dns-packet", "us-east-1")).zone().getId(); zoneIds.add(privateId); change(privateId, "CREATE", record("address." + name, "A", 60, "192.0.2.9")); - assertEquals(List.of("192.0.2.9"), source.resolve("address." + name, 1).orElseThrow().addresses()); - assertFalse(source.resolve("marker." + name, 16).orElseThrow().isPublicAuthorityAnswer()); + DnsClientVpcSource.ClientVpc origin = new DnsClientVpcSource.ClientVpc( + config.defaultAccountId(), "us-east-1", "vpc-dns-packet"); + assertEquals(List.of("192.0.2.9"), source.resolve("address." + name, 1, origin).orElseThrow().addresses()); + assertFalse(source.resolve("marker." + name, 16, origin).orElseThrow().isPublicAuthorityAnswer()); } @Test @@ -453,8 +550,25 @@ class Route53DnsPacketIntegrationTest { assertEquals(length, packet.remaining()); } + private static void assertRuntimeAddress(byte[] response, String address) { + assertEquals(1, ByteBuffer.wrap(response).getShort(6)); + assertArrayEquals(new DnsRecord.Address(1, address).data(), + Arrays.copyOfRange(response, response.length - 4, response.length)); + } + private byte[] query(byte[] request) throws Exception { - EmbeddedDnsServer dns = new EmbeddedDnsServer(List.of("amazonaws.com"), List.of(source)); + return query(request, null); + } + + private byte[] query(byte[] request, String vpcId) throws Exception { + List origins = vpcId == null ? List.of() + : List.of(address -> Optional.of(new DnsClientVpcSource.ClientVpc( + config.defaultAccountId(), "us-east-1", vpcId))); + return queryWithOrigins(request, origins); + } + + private byte[] queryWithOrigins(byte[] request, List runtimeOrigins) throws Exception { + EmbeddedDnsServer dns = new EmbeddedDnsServer(List.of("amazonaws.com"), List.of(source), List.of(), runtimeOrigins); DatagramSocket server = vertx.createDatagramSocket(new DatagramSocketOptions().setIpV6(false)); DatagramSocket client = vertx.createDatagramSocket(new DatagramSocketOptions().setIpV6(false)); try { diff --git a/src/test/java/io/floci/aws/core/common/docker/ContainerLifecycleManagerTeardownTest.java b/src/test/java/io/floci/aws/core/common/docker/ContainerLifecycleManagerTeardownTest.java index 7de74912c7..e0371b0c66 100644 --- a/src/test/java/io/floci/aws/core/common/docker/ContainerLifecycleManagerTeardownTest.java +++ b/src/test/java/io/floci/aws/core/common/docker/ContainerLifecycleManagerTeardownTest.java @@ -14,6 +14,7 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -83,6 +84,50 @@ class ContainerLifecycleManagerTeardownTest { verify(logStream).close(); } + @ParameterizedTest + @ValueSource(strings = {"success", "stopped", "missing", "failed-stop", "failed-both", "failed-remove"}) + void stopNotificationPrecedesRemovalAndRequiresConfirmedTermination(String outcome) throws Exception { + DockerClient docker = mock(DockerClient.class); + ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, docker, null, null, null); + StopContainerCmd stop = mock(StopContainerCmd.class); + when(docker.stopContainerCmd("owned")).thenReturn(stop); + when(stop.withTimeout(5)).thenReturn(stop); + RemoveContainerCmd remove = mock(RemoveContainerCmd.class); + when(docker.removeContainerCmd("owned")).thenReturn(remove); + when(remove.withForce(true)).thenReturn(remove); + AtomicInteger notifications = new AtomicInteger(); + AtomicInteger notificationsBeforeRemoval = new AtomicInteger(-1); + AtomicInteger notificationsBeforeClose = new AtomicInteger(-1); + Closeable stream = () -> notificationsBeforeClose.set(notifications.get()); + if ("stopped".equals(outcome)) { + doThrow(new NotModifiedException("already stopped")).when(stop).exec(); + } else if ("missing".equals(outcome)) { + doThrow(new NotFoundException("already removed")).when(stop).exec(); + } else if ("failed-stop".equals(outcome) || "failed-both".equals(outcome)) { + doThrow(new IllegalStateException("stop failed")).when(stop).exec(); + } + doAnswer(invocation -> { + notificationsBeforeRemoval.set(notifications.get()); + if ("failed-both".equals(outcome) || "failed-remove".equals(outcome)) { + throw new IllegalStateException("remove failed"); + } + return null; + }).when(remove).exec(); + + boolean removed = manager.stopAndConfirmRemoved("owned", stream, 5, true, notifications::incrementAndGet); + + boolean removalFailed = "failed-both".equals(outcome) || "failed-remove".equals(outcome); + assertEquals(!removalFailed, removed); + assertEquals("failed-both".equals(outcome) ? 0 : 1, notifications.get()); + int beforeRemoval = switch (outcome) { + case "missing" -> -1; + case "failed-stop", "failed-both" -> 0; + default -> 1; + }; + assertEquals(beforeRemoval, notificationsBeforeRemoval.get()); + assertEquals(removalFailed ? -1 : 1, notificationsBeforeClose.get()); + } + @ParameterizedTest @ValueSource(strings = {"strict", "strict-volumes", "best-effort", "stop-only"}) void laterOwnedStopsReachDockerWhileEarlierRemovalsAreBlocked(String mode) throws Exception { diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2ContainerManagerTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2ContainerManagerTest.java index abd537cdb1..4c75cead4d 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2ContainerManagerTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2ContainerManagerTest.java @@ -2999,9 +2999,9 @@ class Ec2ContainerManagerTest { int removed = harness.manager.reconcileOrphanedContainers( (region, instanceId) -> "i-live".equals(instanceId)); - verify(harness.lifecycleManager, never()).removeIfExists("c-sibling"); - verify(harness.lifecycleManager, never()).removeIfExists("c-live"); - verify(harness.lifecycleManager).removeIfExists("c-orphan"); + verify(harness.lifecycleManager, never()).removeIfExistsStrict("c-sibling"); + verify(harness.lifecycleManager, never()).removeIfExistsStrict("c-live"); + verify(harness.lifecycleManager).removeIfExistsStrict("c-orphan"); assertEquals(1, removed); } @@ -3015,7 +3015,7 @@ class Ec2ContainerManagerTest { // stop/start across a restart. int removed = harness.manager.reconcileOrphanedContainers((region, instanceId) -> true); - verify(harness.lifecycleManager, never()).removeIfExists(anyString()); + verify(harness.lifecycleManager, never()).removeIfExistsStrict(anyString()); assertEquals(0, removed); } @@ -3031,7 +3031,7 @@ class Ec2ContainerManagerTest { int removed = harness.manager.reconcileOrphanedContainers((region, instanceId) -> false); - verify(harness.lifecycleManager, never()).removeIfExists(anyString()); + verify(harness.lifecycleManager, never()).removeIfExistsStrict(anyString()); assertEquals(0, removed); } @@ -3048,8 +3048,8 @@ class Ec2ContainerManagerTest { int removed = harness.manager.reconcileOrphanedContainers((region, instanceId) -> false); assertEquals(1, removed); - verify(harness.lifecycleManager).removeIfExists("c-ours"); - verify(harness.lifecycleManager, never()).removeIfExists("c-sibling"); + verify(harness.lifecycleManager).removeIfExistsStrict("c-ours"); + verify(harness.lifecycleManager, never()).removeIfExistsStrict("c-sibling"); } @Test @@ -3063,9 +3063,9 @@ class Ec2ContainerManagerTest { int removed = harness.manager.reconcileOrphanedContainers((region, instanceId) -> false); assertEquals(2, removed); - verify(harness.lifecycleManager).removeIfExists("c-legacy"); - verify(harness.lifecycleManager).removeIfExists("c-both"); - verify(harness.lifecycleManager, never()).removeIfExists("c-legacy-sibling"); + verify(harness.lifecycleManager).removeIfExistsStrict("c-legacy"); + verify(harness.lifecycleManager).removeIfExistsStrict("c-both"); + verify(harness.lifecycleManager, never()).removeIfExistsStrict("c-legacy-sibling"); } @Test @@ -3078,7 +3078,7 @@ class Ec2ContainerManagerTest { int removed = harness.manager.reconcileOrphanedContainers((region, instanceId) -> false); assertEquals(0, removed); - verify(harness.lifecycleManager, never()).removeIfExists(anyString()); + verify(harness.lifecycleManager, never()).removeIfExistsStrict(anyString()); } private static Container withOwners(String containerId, Map owners, String instanceId) { @@ -3289,6 +3289,7 @@ class Ec2ContainerManagerTest { awaitUntil(() -> "terminated".equals(instance.getState().getName()), Duration.ofSeconds(2)); assertFalse(ran.get(), "the hook must not run when the container is still present"); + verify(harness.metadataServer()).revokeInstanceCredentials(instance); } @Test diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2DnsLifetimeTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2DnsLifetimeTest.java new file mode 100644 index 0000000000..4754e49330 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/Ec2DnsLifetimeTest.java @@ -0,0 +1,452 @@ +package io.floci.aws.services.ec2; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.InspectContainerCmd; +import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.command.ListContainersCmd; +import com.github.dockerjava.api.command.RemoveContainerCmd; +import com.github.dockerjava.api.command.StartContainerCmd; +import com.github.dockerjava.api.command.StopContainerCmd; +import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.exception.NotModifiedException; +import com.github.dockerjava.api.model.Container; +import com.github.dockerjava.api.model.ContainerNetwork; +import com.github.dockerjava.api.model.NetworkSettings; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.dns.DnsClientVpcSource.ClientVpc; +import io.floci.aws.core.common.docker.ContainerBuilder; +import io.floci.aws.core.common.docker.ContainerDetector; +import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.floci.aws.core.common.docker.ContainerLiveness; +import io.floci.aws.core.common.docker.ContainerLogStreamer; +import io.floci.aws.core.common.docker.ContainerReachableEndpoint; +import io.floci.aws.core.common.docker.DockerHostResolver; +import io.floci.aws.core.common.docker.PortAllocator; +import io.floci.aws.services.ec2.model.Instance; +import io.floci.aws.services.ec2.model.InstanceState; +import io.floci.aws.services.ec2.net.VpcNetworkManager; +import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager; +import io.floci.aws.services.ec2instanceconnect.InstanceConnectKeys; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Answers.RETURNS_DEEP_STUBS; +import static org.mockito.Answers.RETURNS_SELF; +import static org.mockito.Mockito.*; + +class Ec2DnsLifetimeTest { + private static final String ADDRESS = "172.17.0.7"; + private static final String CONTAINER = "ec2-dns-workload"; + + @ParameterizedTest + @CsvSource({"false,success", "true,success", "false,absent", "true,absent", + "false,stopped", "true,stopped", "false,unknown", "true,unknown"}) + void stopRetiresOnlyConfirmedWorkloads(boolean shutdown, String outcome) throws Exception { + try (Fixture fixture = new Fixture(); ExecutorService executor = Executors.newSingleThreadExecutor()) { + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CountDownLatch persisted = new CountDownLatch(1); + fixture.manager.setPersister(instance -> persisted.countDown()); + doAnswer(invocation -> { + entered.countDown(); + release.await(); + switch (outcome) { + case "absent" -> throw new NotFoundException("already removed"); + case "stopped" -> throw new NotModifiedException("already stopped"); + case "unknown" -> throw new IllegalStateException("daemon unavailable"); + default -> { } + } + return null; + }).when(fixture.stop).exec(); + Future request = executor.submit(() -> { + if (shutdown) { + fixture.manager.stopForShutdown(fixture.instance); + } else { + fixture.manager.stop(fixture.instance); + } + }); + try { + assertTrue(entered.await(5, TimeUnit.SECONDS)); + assertTrue(fixture.metadata.vpcForClient(ADDRESS).isPresent(), "graceful stop is still running"); + } finally { + release.countDown(); + } + request.get(5, TimeUnit.SECONDS); + if (!shutdown) { + assertTrue(persisted.await(5, TimeUnit.SECONDS)); + } + assertEquals("unknown".equals(outcome), fixture.metadata.vpcForClient(ADDRESS).isPresent()); + assertSame(fixture.instance, fixture.metadata.registeredContainer(ADDRESS).orElseThrow(), + "protected IMDS registration has a distinct lifetime"); + } + } + + @ParameterizedTest + @CsvSource({"success,false", "absent,false", "unknown,false", "success,true", "absent,true", "none,false"}) + void terminationKeepsOriginUntilRemovalAndRetiresBeforeLaterCleanup(String outcome, boolean reused) + throws Exception { + try (Fixture fixture = new Fixture()) { + CountDownLatch removing = new CountDownLatch(1); + CountDownLatch finishRemoval = new CountDownLatch(1); + CountDownLatch cleaning = new CountDownLatch(1); + CountDownLatch finishCleanup = new CountDownLatch(1); + CountDownLatch persisted = new CountDownLatch(1); + fixture.instance.setSshHostPort(22001); + fixture.manager.setPersister(instance -> persisted.countDown()); + doAnswer(invocation -> { + removing.countDown(); + finishRemoval.await(); + switch (outcome) { + case "absent" -> throw new NotFoundException("already removed"); + case "unknown" -> throw new IllegalStateException("daemon unavailable"); + default -> { } + } + return null; + }).when(fixture.remove).exec(); + doAnswer(invocation -> { + cleaning.countDown(); + finishCleanup.await(); + return null; + }).when(fixture.ports).release(22001); + if ("none".equals(outcome)) { + fixture.instance.setDockerContainerId(null); + } + fixture.manager.terminate(fixture.instance); + try { + if (!"none".equals(outcome)) { + assertTrue(removing.await(5, TimeUnit.SECONDS)); + assertTrue(fixture.metadata.vpcForClient(ADDRESS).isPresent(), + "a container still being removed retains its origin"); + } + if (reused) { + Instance replacement = instance("i-replacement"); + replacement.setVpcId("vpc-other"); + fixture.metadata.registerContainer(ADDRESS, replacement.getInstanceId(), replacement); + } + finishRemoval.countDown(); + assertTrue(cleaning.await(5, TimeUnit.SECONDS)); + assertEquals(reused || "unknown".equals(outcome), + fixture.metadata.vpcForClient(ADDRESS).isPresent(), + "confirmed removal revokes DNS before remaining cleanup"); + } finally { + finishRemoval.countDown(); + finishCleanup.countDown(); + } + assertTrue(persisted.await(5, TimeUnit.SECONDS)); + if (reused) { + assertEquals("vpc-other", fixture.metadata.vpcForClient(ADDRESS).orElseThrow().vpcId()); + } else if ("unknown".equals(outcome)) { + assertSame(fixture.instance, fixture.metadata.registeredContainer(ADDRESS).orElseThrow()); + assertTrue(fixture.metadata.vpcForClient(ADDRESS).isPresent()); + verifyNoInteractions(fixture.networks); + } else { + assertTrue(fixture.metadata.registeredContainer(ADDRESS).isEmpty()); + verify(fixture.networks).releasePrivateIp(fixture.instance.getOwnerId(), + fixture.instance.getRegion(), fixture.instance.getSubnetId(), + fixture.instance.getPrivateIpAddress()); + } + } + } + + @Test + void stoppedInstanceCannotRevokeAnAddressReassignedToAnotherWorkload() { + try (Fixture fixture = new Fixture()) { + Instance replacement = instance("i-replacement"); + replacement.setVpcId("vpc-other"); + fixture.metadata.registerContainer(ADDRESS, replacement.getInstanceId(), replacement); + fixture.manager.stopForShutdown(fixture.instance); + assertEquals("vpc-other", fixture.metadata.vpcForClient(ADDRESS).orElseThrow().vpcId()); + } + } + + @ParameterizedTest + @CsvSource({"false", "true"}) + void restartKeepsDnsInactiveUntilConfirmedRunning(boolean failed) throws Exception { + try (Fixture fixture = new Fixture()) { + fixture.manager.stopForShutdown(fixture.instance); + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CountDownLatch persisted = new CountDownLatch(1); + fixture.manager.setPersister(instance -> persisted.countDown()); + doAnswer(invocation -> { + entered.countDown(); + release.await(); + if (failed) { + throw new IllegalStateException("start failed"); + } + return null; + }).when(fixture.start).exec(); + fixture.manager.start(fixture.instance); + try { + assertTrue(entered.await(5, TimeUnit.SECONDS)); + assertTrue(fixture.metadata.vpcForClient(ADDRESS).isEmpty()); + assertSame(fixture.instance, fixture.metadata.registeredContainer(ADDRESS).orElseThrow()); + } finally { + release.countDown(); + } + assertTrue(persisted.await(5, TimeUnit.SECONDS)); + assertEquals(!failed, fixture.metadata.vpcForClient(ADDRESS).isPresent()); + } + } + + @Test + void restoreOfRunningWorkloadReactivatesDns() { + try (Fixture fixture = new Fixture()) { + fixture.manager.stopForShutdown(fixture.instance); + assertTrue(fixture.metadata.vpcForClient(ADDRESS).isEmpty()); + assertTrue(fixture.manager.restoreMetadataRegistration(fixture.instance)); + assertTrue(fixture.metadata.vpcForClient(ADDRESS).isPresent()); + } + } + + @ParameterizedTest + @CsvSource({"false", "true"}) + void laterShutdownWinsOverEarlierRunningObservation(boolean restore) throws Exception { + try (Fixture fixture = new Fixture(); ExecutorService executor = Executors.newSingleThreadExecutor()) { + fixture.manager.stopForShutdown(fixture.instance); + CountDownLatch observedRunning = new CountDownLatch(1); + CountDownLatch inspecting = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CountDownLatch done = new CountDownLatch(1); + fixture.manager.setPersister(instance -> done.countDown()); + when(fixture.lifecycle.isContainerRunning(CONTAINER)).thenAnswer(invocation -> { + observedRunning.countDown(); + return true; + }); + when(fixture.inspect.exec()).thenAnswer(invocation -> { + if (observedRunning.getCount() == 0) { + inspecting.countDown(); + release.await(); + } + return fixture.response; + }); + Future request = executor.submit(() -> { + if (restore) { + fixture.manager.restoreMetadataRegistration(fixture.instance); + done.countDown(); + } else { + fixture.manager.start(fixture.instance); + } + }); + try { + assertTrue(inspecting.await(5, TimeUnit.SECONDS)); + fixture.manager.stopForShutdown(fixture.instance); + } finally { + release.countDown(); + } + request.get(5, TimeUnit.SECONDS); + assertTrue(done.await(5, TimeUnit.SECONDS)); + assertTrue(fixture.metadata.vpcForClient(ADDRESS).isEmpty(), + "an old running observation must not reactivate a subsequently stopped workload"); + } + } + + @Test + void metadataStopDiscardsOldDnsSuspension() { + try (Fixture fixture = new Fixture()) { + fixture.manager.stopForShutdown(fixture.instance); + assertTrue(fixture.metadata.vpcForClient(ADDRESS).isEmpty()); + fixture.metadata.stop(); + fixture.metadata.registerContainer(ADDRESS, fixture.instance.getInstanceId(), fixture.instance); + assertTrue(fixture.metadata.vpcForClient(ADDRESS).isPresent()); + } + } + + @ParameterizedTest + @CsvSource({"NOT_RUNNING,true", "RUNNING,false", "UNKNOWN,false"}) + void recoveryProbeRetiresDnsOnlyAfterConfirmedStop(ContainerLiveness liveness, boolean stopped) { + try (Fixture fixture = new Fixture()) { + doThrow(new IllegalStateException("stop result unavailable")).when(fixture.stop).exec(); + when(fixture.lifecycle.probeContainer(CONTAINER)).thenReturn(liveness); + assertEquals(stopped, fixture.manager.stopAndConfirm(fixture.instance)); + assertEquals(!stopped, fixture.metadata.vpcForClient(ADDRESS).isPresent()); + assertSame(fixture.instance, fixture.metadata.registeredContainer(ADDRESS).orElseThrow()); + } + } + + @ParameterizedTest + @CsvSource({"remove", "replace", "suspend", "unchanged"}) + void dnsLookupRechecksOwnershipAfterReadingInstance(String change) throws Exception { + try (Fixture fixture = new Fixture(); ExecutorService executor = Executors.newSingleThreadExecutor()) { + Instance observed = spy(instance("i-observed")); + fixture.metadata.registerContainer(ADDRESS, observed.getInstanceId(), observed); + CountDownLatch reading = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + doAnswer(invocation -> { + reading.countDown(); + release.await(); + return "123456789012"; + }).when(observed).getOwnerId(); + Future> lookup = executor.submit(() -> fixture.metadata.vpcForClient(ADDRESS)); + try { + assertTrue(reading.await(5, TimeUnit.SECONDS)); + switch (change) { + case "remove" -> fixture.metadata.unregisterInstance(observed); + case "replace" -> { + Instance replacement = instance("i-new-owner"); + replacement.setVpcId("vpc-new-owner"); + fixture.metadata.registerContainer(ADDRESS, replacement.getInstanceId(), replacement); + fixture.metadata.unregisterInstance(observed); + assertEquals("vpc-new-owner", fixture.metadata.vpcForClient(ADDRESS).orElseThrow().vpcId()); + } + case "suspend" -> fixture.metadata.suspendDns(observed); + default -> { } + } + } finally { + release.countDown(); + } + assertEquals("unchanged".equals(change), lookup.get(5, TimeUnit.SECONDS).isPresent(), + "a captured instance must not restore revoked or reassigned DNS scope"); + } + } + + @Test + void recoveryWithoutContainerRetiresRegisteredOrigin() { + try (Fixture fixture = new Fixture()) { + fixture.instance.setDockerContainerId(null); + assertTrue(fixture.manager.stopAndConfirm(fixture.instance)); + assertTrue(fixture.metadata.vpcForClient(ADDRESS).isEmpty()); + assertSame(fixture.instance, fixture.metadata.registeredContainer(ADDRESS).orElseThrow()); + } + } + + @ParameterizedTest + @CsvSource({"false", "true"}) + void unregisterInvalidatesOlderResumeWithoutBlockingNewObservation(boolean freshObservation) { + try (Fixture fixture = new Fixture()) { + Ec2MetadataServer.DnsSuspension observed = fixture.metadata.suspendDns(fixture.instance); + fixture.metadata.unregisterInstance(fixture.instance); + fixture.metadata.registerContainer(ADDRESS, fixture.instance.getInstanceId(), fixture.instance); + if (freshObservation) { + observed = fixture.metadata.dnsSuspension(fixture.instance); + } + fixture.metadata.resumeDns(fixture.instance, observed); + assertEquals(freshObservation, fixture.metadata.vpcForClient(ADDRESS).isPresent()); + } + } + + @ParameterizedTest + @CsvSource({"success,none", "absent,none", "unknown,none", "success,address", "unknown,address", + "success,container", "absent,container"}) + void orphanReconciliationRetiresOnlyConfirmedMatchingTransport(String outcome, String reuse) throws Exception { + try (Fixture fixture = new Fixture(); ExecutorService executor = Executors.newSingleThreadExecutor()) { + CountDownLatch removing = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + doAnswer(invocation -> { + removing.countDown(); + release.await(); + if ("unknown".equals(outcome)) { + throw new IllegalStateException("daemon unavailable"); + } + if ("absent".equals(outcome)) { + throw new NotFoundException("already removed"); + } + return null; + }).when(fixture.remove).exec(); + doAnswer(invocation -> { + fixture.actualLifecycle.removeIfExistsStrict(CONTAINER); + return null; + }).when(fixture.lifecycle).removeIfExistsStrict(CONTAINER); + doAnswer(invocation -> { + fixture.actualLifecycle.removeIfExists(CONTAINER); + return null; + }).when(fixture.lifecycle).removeIfExists(CONTAINER); + Future request = executor.submit(() -> fixture.manager.reconcileOrphanedContainers( + (region, instanceId) -> false)); + boolean reused = !"none".equals(reuse); + Instance replacement = "container".equals(reuse) ? fixture.instance : instance("i-replacement"); + try { + assertTrue(removing.await(5, TimeUnit.SECONDS)); + assertTrue(fixture.metadata.vpcForClient(ADDRESS).isPresent(), "removal is not confirmed yet"); + if (reused) { + replacement.setDockerContainerId("replacement-container"); + fixture.metadata.registerContainer(ADDRESS, replacement.getInstanceId(), replacement); + } + } finally { + release.countDown(); + } + assertEquals("unknown".equals(outcome) ? 0 : 1, request.get(5, TimeUnit.SECONDS)); + assertEquals(reused || "unknown".equals(outcome), fixture.metadata.vpcForClient(ADDRESS).isPresent()); + assertSame(reused ? replacement : fixture.instance, + fixture.metadata.registeredContainer(ADDRESS).orElseThrow()); + } + } + + private static Instance instance(String id) { + Instance instance = new Instance(); + instance.setInstanceId(id); + instance.setDockerContainerId(CONTAINER); + instance.setOwnerId("123456789012"); + instance.setRegion("us-east-1"); + instance.setVpcId("vpc-dns"); + instance.setContainerBridgeIp(ADDRESS); + instance.setState(InstanceState.running()); + return instance; + } + + private static class Fixture implements AutoCloseable { + private final ContainerLifecycleManager actualLifecycle; + private final Ec2MetadataServer metadata = new Ec2MetadataServer(null, null, null, (InstanceConnectKeys) null); + private final Instance instance = instance("i-dns"); + private final StopContainerCmd stop = mock(StopContainerCmd.class, RETURNS_SELF); + private final RemoveContainerCmd remove = mock(RemoveContainerCmd.class, RETURNS_SELF); + private final PortAllocator ports = mock(PortAllocator.class); + private final VpcNetworkManager networks = mock(VpcNetworkManager.class); + private final StartContainerCmd start = mock(StartContainerCmd.class, RETURNS_SELF); + private final Ec2ContainerManager manager; + private final InspectContainerCmd inspect = mock(InspectContainerCmd.class); + private final InspectContainerResponse response = mock(InspectContainerResponse.class); + private final ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); + + Fixture() { + DockerClient docker = mock(DockerClient.class); + ListContainersCmd listing = mock(ListContainersCmd.class, RETURNS_SELF); + Container container = mock(Container.class); + when(container.getId()).thenReturn(CONTAINER); + when(container.getLabels()).thenReturn(Map.of( + Ec2ContainerManager.LABEL_SERVICE, Ec2ContainerManager.SERVICE_VALUE, + Ec2ContainerManager.LABEL_OWNER, "4566", + Ec2ContainerManager.LABEL_REGION, "us-east-1", + Ec2ContainerManager.LABEL_RESOURCE_ID, "i-dns")); + when(docker.listContainersCmd()).thenReturn(listing); + when(listing.exec()).thenReturn(List.of(container)); + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + actualLifecycle = new ContainerLifecycleManager(docker, docker, null, null, config); + when(config.port()).thenReturn(4566); + when(config.services().ec2().reconcileContainersOnStartup()).thenReturn(true); + when(docker.removeContainerCmd(CONTAINER)).thenReturn(remove); + when(docker.stopContainerCmd(CONTAINER)).thenReturn(stop); + when(docker.startContainerCmd(CONTAINER)).thenReturn(start); + when(docker.inspectContainerCmd(CONTAINER)).thenReturn(inspect); + NetworkSettings networks = mock(NetworkSettings.class); + when(response.getNetworkSettings()).thenReturn(networks); + when(networks.getNetworks()).thenReturn(Map.of("bridge", new ContainerNetwork().withIpv4Address(ADDRESS))); + when(inspect.exec()).thenReturn(response); + when(lifecycle.isContainerRunning(CONTAINER)).thenReturn(true); + manager = new Ec2ContainerManager(mock(ContainerBuilder.class), lifecycle, + mock(ContainerLogStreamer.class), mock(ContainerDetector.class), mock(DockerHostResolver.class), + docker, ports, config, metadata, + mock(Ec2PortForwardManager.class), mock(RegionResolver.class), + mock(ContainerNetworkReachability.class), this.networks, + mock(ContainerReachableEndpoint.class)); + metadata.registerContainer(ADDRESS, instance.getInstanceId(), instance); + } + + @Override + public void close() { + manager.stop(); + } + } +} diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2InstanceCredentialsIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2InstanceCredentialsIntegrationTest.java index e8f43d5633..a4746ae0a7 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2InstanceCredentialsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2InstanceCredentialsIntegrationTest.java @@ -25,8 +25,8 @@ class Ec2InstanceCredentialsIntegrationTest { IamService iam; @ParameterizedTest - @ValueSource(booleans = {false, true}) - void imdsCredentialsResolveToTheAttachedRoleAndAreRevokedOnCleanup(boolean stopServer) throws Exception { + @ValueSource(strings = {"stop", "unregister", "revoke"}) + void imdsCredentialsResolveToTheAttachedRoleAndAreRevokedOnCleanup(String cleanup) throws Exception { String account = "246813579012"; String suffix = UUID.randomUUID().toString().substring(0, 8); String role = "worker-" + suffix; @@ -68,14 +68,22 @@ class Ec2InstanceCredentialsIntegrationTest { assertEquals("arn:aws:sts::" + account + ":assumed-role/" + role + "/i-credentials", iam.resolveCallerArn(key).orElseThrow()); assertEquals(response.body(), fixture.get(path + role, token.body()).body()); - if (stopServer) { + if ("stop".equals(cleanup)) { server.stop(); } else { - server.unregisterInstance(instance); + if ("revoke".equals(cleanup)) { + server.revokeInstanceCredentials(instance); + } else { + server.unregisterInstance(instance); + } assertNotEquals(200, fixture.get(path + role, token.body()).statusCode()); } assertTrue(iam.findSecretKey(key, sessionToken).isEmpty()); - assertTrue(server.registeredContainer("127.0.0.1").isEmpty()); + assertEquals("revoke".equals(cleanup), server.registeredContainer("127.0.0.1").isPresent()); + if ("revoke".equals(cleanup)) { + server.registerContainer("127.0.0.1", instance.getInstanceId(), instance); + assertNotEquals(200, fixture.get(path + role, fixture.putToken("60").body()).statusCode()); + } } finally { given().header("Authorization", auth).contentType("application/x-www-form-urlencoded") .formParam("Action", "RemoveRoleFromInstanceProfile").formParam("InstanceProfileName", profile) diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2MetadataServerTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2MetadataServerTest.java index 3a8210db69..672e46b69b 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2MetadataServerTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2MetadataServerTest.java @@ -1,5 +1,6 @@ package io.floci.aws.services.ec2; +import io.floci.aws.core.common.dns.DnsClientVpcSource.ClientVpc; import io.floci.aws.services.ec2.model.Instance; import io.floci.aws.services.ec2.model.InstanceNetworkInterface; import io.floci.aws.services.ec2.model.Placement; @@ -9,6 +10,7 @@ import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -35,6 +37,61 @@ class Ec2MetadataServerTest { assertEquals(second, server.registeredContainer("192.0.2.3").orElseThrow()); } + @Test + void dnsOriginFollowsAddressReconciliationAndInstanceRemoval() { + Ec2MetadataServer server = new Ec2MetadataServer(null, null, null, (InstanceConnectKeys) null); + Instance instance = dnsInstance("111111111111", "us-west-2", "vpc-one"); + ClientVpc expected = new ClientVpc("111111111111", "us-west-2", "vpc-one"); + server.reconcileContainerAddresses(Set.of("192.0.2.1", "2001:db8::1"), instance); + assertEquals(Optional.of(expected), server.vpcForClient("192.0.2.1")); + assertEquals(Optional.of(expected), server.vpcForClient("2001:db8::1")); + server.reconcileContainerAddresses(Set.of("192.0.2.2"), instance); + assertTrue(server.vpcForClient("192.0.2.1").isEmpty()); + assertTrue(server.vpcForClient("2001:db8::1").isEmpty()); + assertEquals(Optional.of(expected), server.vpcForClient("192.0.2.2")); + server.unregisterInstance(instance); + assertTrue(server.vpcForClient("192.0.2.2").isEmpty()); + } + + @Test + void dnsOriginPreservesReplacementOwnerWhenOldInstanceCleansUp() { + Ec2MetadataServer server = new Ec2MetadataServer(null, null, null, (InstanceConnectKeys) null); + Instance first = dnsInstance("111111111111", "us-west-2", "vpc-one"); + Instance replacement = dnsInstance("222222222222", "us-east-1", "vpc-two"); + server.registerContainer("192.0.2.1", "first", first); + server.registerContainer("192.0.2.1", "replacement", replacement); + server.unregisterContainer("192.0.2.1", first); + server.unregisterInstance(first); + assertEquals(Optional.of(new ClientVpc("222222222222", "us-east-1", "vpc-two")), + server.vpcForClient("192.0.2.1")); + server.rollbackContainerRegistration("192.0.2.1", replacement); + assertTrue(server.vpcForClient("192.0.2.1").isEmpty()); + } + + @Test + void dnsOriginDoesNotInferMissingIdentityOrTrustAMetadataRelay() { + Ec2MetadataServer server = new Ec2MetadataServer(null, null, null, (InstanceConnectKeys) null); + server.trustForwarder("192.0.2.1"); + assertTrue(server.vpcForClient("192.0.2.1").isEmpty()); + assertTrue(server.vpcForClient(null).isEmpty()); + assertTrue(server.vpcForClient("").isEmpty()); + for (Instance incomplete : List.of(dnsInstance(null, "us-east-1", "vpc-one"), + dnsInstance("111111111111", "", "vpc-one"), + dnsInstance("111111111111", "us-east-1", null))) { + server.registerContainer("192.0.2.1", "incomplete", incomplete); + assertTrue(server.vpcForClient("192.0.2.1").isEmpty()); + } + } + + private static Instance dnsInstance(String owner, String region, String vpc) { + Instance instance = new Instance(); + instance.setInstanceId("i-dns"); + instance.setOwnerId(owner); + instance.setRegion(region); + instance.setVpcId(vpc); + return instance; + } + @Test void instanceMetadataListsTagKeys() { Instance instance = new Instance(); diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2MetadataTokenTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2MetadataTokenTest.java index 3dc5d580a9..b0b393c4b1 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2MetadataTokenTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2MetadataTokenTest.java @@ -45,6 +45,20 @@ class Ec2MetadataTokenTest { assertEquals(400, fixture.putToken(ttl).statusCode()); } + @Test + void credentialRevocationKeepsTransportOwnershipButRefusesOldAndNewTokens() throws Exception { + Ec2MetadataServer server = fixture.server(); + String token = fixture.putToken("60").body(); + assertEquals(200, getInstanceId(token).statusCode()); + + server.revokeInstanceCredentials(instance); + assertEquals(instance, server.registeredContainer("127.0.0.1").orElseThrow()); + assertEquals(404, getInstanceId(token).statusCode()); + assertEquals(404, getWithoutToken("/latest/meta-data/instance-id").statusCode()); + server.registerContainer("127.0.0.1", instance.getInstanceId(), instance); + assertEquals(404, getInstanceId(fixture.putToken("60").body()).statusCode()); + } + @Test void tokenWithTheMaximumTtlIsIssued() throws Exception { HttpResponse token = fixture.putToken("21600"); diff --git a/src/test/java/io/floci/aws/services/ecs/EcsServiceDaemonSchedulingTest.java b/src/test/java/io/floci/aws/services/ecs/EcsServiceDaemonSchedulingTest.java index 4309a372a6..c37e734835 100644 --- a/src/test/java/io/floci/aws/services/ecs/EcsServiceDaemonSchedulingTest.java +++ b/src/test/java/io/floci/aws/services/ecs/EcsServiceDaemonSchedulingTest.java @@ -1,6 +1,7 @@ package io.floci.aws.services.ecs; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.dns.DnsClientVpcSource.ClientVpc; import io.floci.aws.services.ecs.container.EcsContainerManager; import io.floci.aws.services.ecs.container.EcsTaskHandle; import io.floci.aws.services.ecs.model.ContainerDefinition; @@ -15,6 +16,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -24,7 +26,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** DAEMON scheduling: one task per ACTIVE container instance, nothing else. */ @@ -32,6 +36,54 @@ class EcsServiceDaemonSchedulingTest { private static final String REGION = "us-east-1"; + @Test + void daemonLaunchCarriesTheRegisteredEc2HostsVpc() { + EcsContainerManager manager = mock(EcsContainerManager.class); + when(manager.removeLeftoverContainers()).thenReturn(true); + // Both launch paths succeed: the assertion detects lost host context, not a null mock handle. + when(manager.startTask(any(), any(), any(), eq(REGION))).thenAnswer(invocation -> + new EcsTaskHandle(invocation.getArgument(0).getTaskArn(), Map.of("agent", "cid"), Map.of())); + EcsService service = EcsServiceFixtures.builder().dockerMode().containerManager(manager).build(); + try { + service.createCluster("daemon-origin", REGION); + ContainerInstance host = service.registerContainerInstance("daemon-origin", null, List.of(), REGION); + ClientVpc origin = new ClientVpc("000000000000", REGION, "vpc-host"); + when(manager.vpcForInstance("000000000000", REGION, host.getEc2InstanceId())) + .thenReturn(Optional.of(origin)); + when(manager.startTask(any(), any(), any(), eq(REGION), eq(origin))).thenAnswer(invocation -> + new EcsTaskHandle(invocation.getArgument(0).getTaskArn(), Map.of("agent", "cid"), Map.of())); + registerTaskDef(service); + service.createService("daemon-origin", "daemon-svc", "daemon-fam", 1, LaunchType.EC2, + List.of(), null, null, "DAEMON", null, null, REGION); + service.reconcileServices(); + assertEquals(1, runningTasks(service).size()); + verify(manager).startTask(any(), any(), any(), eq(REGION), eq(origin)); + } finally { + service.beginTeardown(); + } + } + + @Test + void unknownRegisteredHostDoesNotInventVpcContext() { + EcsContainerManager manager = mock(EcsContainerManager.class); + when(manager.removeLeftoverContainers()).thenReturn(true); + when(manager.startTask(any(), any(), any(), eq(REGION))).thenAnswer(invocation -> + new EcsTaskHandle(invocation.getArgument(0).getTaskArn(), Map.of("agent", "cid"), Map.of())); + EcsService service = EcsServiceFixtures.builder().dockerMode().containerManager(manager).build(); + try { + service.createCluster("daemon-unknown-origin", REGION); + service.registerContainerInstance("daemon-unknown-origin", null, List.of(), REGION); + registerTaskDef(service); + service.createService("daemon-unknown-origin", "daemon-svc", "daemon-fam", 1, LaunchType.EC2, + List.of(), null, null, "DAEMON", null, null, REGION); + service.reconcileServices(); + assertEquals(1, runningTasks(service).size()); + verify(manager).startTask(any(), any(), any(), eq(REGION)); + } finally { + service.beginTeardown(); + } + } + @Test void daemonServiceRunsExactlyOneTaskPerActiveContainerInstance() { EcsService service = EcsServiceFixtures.mockModeService(); diff --git a/src/test/java/io/floci/aws/services/ecs/EcsServiceTeardownTest.java b/src/test/java/io/floci/aws/services/ecs/EcsServiceTeardownTest.java index ae72c627ea..1973c8eff7 100644 --- a/src/test/java/io/floci/aws/services/ecs/EcsServiceTeardownTest.java +++ b/src/test/java/io/floci/aws/services/ecs/EcsServiceTeardownTest.java @@ -110,6 +110,68 @@ class EcsServiceTeardownTest { assertEquals(2, attempts.get(), "cleanup stops retrying after the volume is removed"); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void stoppedTaskRetriesNetworkReleaseAfterNamespaceCleanup(boolean exitsNaturally) { + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().ecs().mock()).thenReturn(false); + when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566"); + EcsContainerManager manager = mock(EcsContainerManager.class); + EcsTaskHandle handle = new EcsTaskHandle("task-arn", Map.of("app", "docker-id"), Map.of()); + handle.recordNamespaceHelperPending(true); + when(manager.startTask(any(), any(), any(), anyString())).thenReturn(handle); + when(manager.getExitCodeIfStopped("docker-id")).thenReturn(0); + AtomicInteger attempts = new AtomicInteger(); + doAnswer(ignored -> { + attempts.incrementAndGet(); + handle.recordContainerRemoved("app"); + return null; + }).when(manager).cleanupStoppedTask(handle); + when(manager.stopTaskAndCollectExitCodes(handle)).thenAnswer(ignored -> { + handle.recordContainerRemoved("app"); + if (attempts.incrementAndGet() == 3) { + handle.recordNamespaceHelperPending(false); + } + return Map.of("app", 0); + }); + doAnswer(invocation -> { + EcsTask task = invocation.getArgument(0); + if (!handle.isNamespaceHelperPending()) { + task.setAttachmentStatus("DELETED"); + } + return null; + }).when(manager).releaseTaskNetwork(any(), anyString()); + EcsService service = new EcsService(new RegionResolver(REGION, "000000000000"), manager, config, + mock(EcsLoadBalancerRegistrar.class), new SingleUseStorageFactory(), null); + service.initializeStorage(); + ContainerDefinition definition = new ContainerDefinition(); + definition.setName("app"); + definition.setImage("app:latest"); + service.registerTaskDefinition("network-retry", List.of(definition), null, null, null, + null, null, List.of(), REGION); + String taskArn = service.runTask(null, "network-retry", 1, LaunchType.FARGATE, null, null, + List.of(), null, REGION).getFirst().getTaskArn(); + EcsTask task = awaitLastStatus(() -> service.describeTasks(null, List.of(taskArn), REGION).getFirst(), + EcsTask::getLastStatus, Duration.ofSeconds(5), "RUNNING"); + task.setNetworkInterfaceId("eni-retry"); + task.setAttachmentStatus("ATTACHED"); + if (exitsNaturally) { + service.reconcile(); + } else { + service.stopTask(null, taskArn, null, REGION); + } + assertEquals("STOPPED", task.getLastStatus()); + assertEquals("ATTACHED", task.getAttachmentStatus()); + service.reconcile(); + assertTrue(handle.isNamespaceHelperPending()); + assertEquals("ATTACHED", task.getAttachmentStatus()); + service.reconcile(); + assertFalse(handle.isNamespaceHelperPending()); + assertEquals("DELETED", task.getAttachmentStatus()); + service.reconcile(); + assertEquals(3, attempts.get(), "successful cleanup retires the pending handle"); + } + @Test void failedLaunchCleanupIsRetriedByStoppedTaskReconciliation() { EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); diff --git a/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerSharedTaskNetworkTest.java b/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerSharedTaskNetworkTest.java index 0b4ec8c7a5..3472c59811 100644 --- a/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerSharedTaskNetworkTest.java +++ b/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerSharedTaskNetworkTest.java @@ -7,6 +7,7 @@ import com.github.dockerjava.api.command.InspectVolumeResponse; import com.github.dockerjava.api.command.RemoveContainerCmd; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.dns.DnsClientVpcSource.ClientVpc; import io.floci.aws.core.common.docker.ContainerBuilder; import io.floci.aws.core.common.docker.ContainerDetector; import io.floci.aws.core.common.docker.ContainerLifecycleManager; @@ -56,6 +57,7 @@ import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.RETURNS_SELF; import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -94,7 +96,7 @@ class EcsContainerManagerSharedTaskNetworkTest { lifecycleManager = mock(ContainerLifecycleManager.class); // Its confirmed removal goes through the strict removal each test stubs. - when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean())).thenCallRealMethod(); + when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean(), any())).thenCallRealMethod(); when(lifecycleManager.resolveImageForLaunch(any(), any(), any())) .thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null)); when(lifecycleManager.createAndStartEphemeral(any(), any())).thenReturn(new ContainerInfo("docker-id", Map.of())); @@ -128,6 +130,42 @@ class EcsContainerManagerSharedTaskNetworkTest { linkLocalAddresses); } + @Test + void sharedNamespacePublishesDnsBeforeWorkloadStartsAndRevokesOnCleanup() { + Subnet subnet = new Subnet(); + subnet.setVpcId("vpc-dns"); + when(ec2Service.describeSubnets(eq("us-east-1"), eq(List.of("subnet-1")), any())) + .thenReturn(List.of(subnet)); + ClientVpc expected = new ClientVpc("000000000000", "us-east-1", "vpc-dns"); + when(lifecycleManager.createAndStartEphemeral(any(), any())).thenAnswer(invocation -> { + assertEquals(Optional.of(expected), manager.vpcForClient("172.18.0.9")); + return new ContainerInfo("docker-id", Map.of()); + }); + EcsTaskHandle handle = manager.startTask(awsvpcTask(), taskDef(null, container("web", 80)), + List.of(), "us-east-1"); + assertEquals(Optional.of(expected), manager.vpcForClient("172.18.0.9")); + manager.cleanupStoppedTask(handle); + assertTrue(manager.vpcForClient("172.18.0.9").isEmpty()); + } + + @Test + void sharedDnsOwnershipSurvivesWorkloadStopsAndFailedHelperRemoval() { + Subnet subnet = new Subnet(); + subnet.setVpcId("vpc-dns"); + when(ec2Service.describeSubnets(eq("us-east-1"), eq(List.of("subnet-1")), any())) + .thenReturn(List.of(subnet)); + EcsTaskHandle handle = manager.startTask(awsvpcTask(), taskDef(null, container("web", 80)), + List.of(), "us-east-1"); + ClientVpc expected = new ClientVpc("000000000000", "us-east-1", "vpc-dns"); + doThrow(new IllegalStateException("helper still running")) + .when(firewallManager).removeSharedNamespaceStrict("abc123"); + assertThrows(IllegalStateException.class, () -> manager.stopTaskAndCollectExitCodes(handle)); + assertEquals(Optional.of(expected), manager.vpcForClient("172.18.0.9")); + doNothing().when(firewallManager).removeSharedNamespaceStrict("abc123"); + manager.cleanupStoppedTask(handle); + assertTrue(manager.vpcForClient("172.18.0.9").isEmpty()); + } + @Test void everyContainerJoinsOneHelperThatHoldsTheTasksPorts() { EcsTaskHandle handle = manager.startTask(awsvpcTask(), taskDef(null, @@ -313,7 +351,7 @@ class EcsContainerManagerSharedTaskNetworkTest { assertThrows(IllegalStateException.class, () -> manager.startTask(awsvpcTask(), taskDef(null, container("web", 8081)), List.of(), "us-east-1")); - verify(lifecycleManager).stopAndRemoveStrict(eq("docker-id"), any(), anyInt(), anyBoolean()); + verify(lifecycleManager).stopAndRemoveStrict(eq("docker-id"), any(), anyInt(), anyBoolean(), any()); verify(firewallManager).removeSharedNamespaceStrict("abc123"); } diff --git a/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerTaskAddressTest.java b/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerTaskAddressTest.java index ff91121342..9b08147b88 100644 --- a/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerTaskAddressTest.java +++ b/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerTaskAddressTest.java @@ -1,11 +1,18 @@ package io.floci.aws.services.ecs.container; import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.InspectContainerCmd; import com.github.dockerjava.api.command.InspectContainerResponse; +import com.github.dockerjava.api.command.KillContainerCmd; +import com.github.dockerjava.api.command.RemoveContainerCmd; +import com.github.dockerjava.api.command.StopContainerCmd; +import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.exception.NotModifiedException; import com.github.dockerjava.api.model.ContainerNetwork; import com.github.dockerjava.api.model.HostConfig; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.dns.DnsClientVpcSource.ClientVpc; import io.floci.aws.core.common.docker.ContainerBuilder; import io.floci.aws.core.common.docker.ContainerDetector; import io.floci.aws.core.common.docker.ContainerLifecycleManager; @@ -15,6 +22,8 @@ import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv; import io.floci.aws.services.ec2.Ec2Service; import io.floci.aws.services.ec2.SecurityGroupFirewallManager; import io.floci.aws.services.ec2.model.GroupIdentifier; +import io.floci.aws.services.ec2.model.Instance; +import io.floci.aws.services.ec2.model.InstanceState; import io.floci.aws.services.ec2.model.NetworkInterface; import io.floci.aws.services.ec2.model.SecurityGroup; import io.floci.aws.services.ec2.model.Subnet; @@ -34,22 +43,36 @@ import io.floci.aws.services.ssm.SsmService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; import org.junit.jupiter.params.provider.ValueSource; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.RETURNS_SELF; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; /** @@ -82,6 +105,7 @@ class EcsContainerManagerTaskAddressTest { .thenReturn(new ContainerInfo("sidecar-id", Map.of()), new ContainerInfo("web-id", Map.of())); dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS); when(lifecycleManager.getDockerClient()).thenReturn(dockerClient); + when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean(), any())).thenReturn(true); ContainerDetector containerDetector = mock(ContainerDetector.class); EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); @@ -109,6 +133,321 @@ class EcsContainerManagerTaskAddressTest { new EcsTaskLinkLocalAddresses()); } + @ParameterizedTest + @ValueSource(strings = {"bridge", "host"}) + void registeredHostVpcScopesTaskAddresses(String mode) { + dnsAttachments("sidecar-id", "172.17.0.5", "2001:db8::5"); + EcsTask task = taskWithEni(); + task.setNetworkInterfaceId(null); + ClientVpc origin = new ClientVpc("000000000000", REGION, "vpc-host"); + EcsTaskHandle handle = manager.startTask(task, taskDefinition(NetworkMode.valueOf(mode), + container("web", List.of())), List.of(), REGION, origin); + assertEquals(Optional.of(origin), manager.vpcForClient("172.17.0.5")); + manager.cleanupStoppedTask(handle); + assertTrue(manager.vpcForClient("172.17.0.5").isEmpty()); + } + + @Test + void gracefulStopKeepsLiveSiblingOriginsAndRevokesEachStoppedAddress() throws Exception { + dnsAttachments("sidecar-id", "172.17.0.5", "2001:db8::5"); + dnsAttachments("web-id", "172.17.0.6", "2001:db8::6"); + EcsTaskHandle handle = manager.startTask(taskWithEni(), taskDefinition(NetworkMode.awsvpc, + container("sidecar", List.of()), container("web", List.of())), List.of(), REGION); + ClientVpc expected = new ClientVpc("000000000000", REGION, "vpc-1"); + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + StopContainerCmd firstStop = dockerClient.stopContainerCmd("sidecar-id") + .withTimeout(handle.stopTimeoutFor("sidecar")); + StopContainerCmd secondStop = dockerClient.stopContainerCmd("web-id") + .withTimeout(handle.stopTimeoutFor("web")); + doAnswer(invocation -> { + entered.countDown(); + release.await(); + return null; + }).when(firstStop).exec(); + doAnswer(invocation -> { + assertTrue(manager.vpcForClient("172.17.0.5").isEmpty()); + assertTrue(manager.vpcForClient("2001:db8::5").isEmpty()); + assertEquals(Optional.of(expected), manager.vpcForClient("172.17.0.6")); + assertEquals(Optional.of(expected), manager.vpcForClient("2001:db8::6")); + return null; + }).when(secondStop).exec(); + try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { + Future> stopped = executor.submit(() -> manager.stopTaskAndCollectExitCodes(handle)); + try { + assertTrue(entered.await(5, TimeUnit.SECONDS)); + assertEquals(Optional.of(expected), manager.vpcForClient("172.17.0.5")); + assertEquals(Optional.of(expected), manager.vpcForClient("172.17.0.6")); + } finally { + release.countDown(); + } + stopped.get(5, TimeUnit.SECONDS); + } + assertTrue(manager.vpcForClient("172.17.0.5").isEmpty()); + assertTrue(manager.vpcForClient("172.17.0.6").isEmpty()); + } + + @ParameterizedTest + @ValueSource(strings = {"success", "missing", "stopped"}) + void confirmedStopRevokesOriginBeforeBlockingExitInspection(String outcome) throws Exception { + dnsAttachments("sidecar-id", "172.17.0.5", "2001:db8::5"); + EcsTaskHandle handle = manager.startTask(taskWithEni(), + taskDefinition(NetworkMode.awsvpc, container("web", List.of())), List.of(), REGION); + StopContainerCmd stop = dockerClient.stopContainerCmd("sidecar-id") + .withTimeout(handle.stopTimeoutFor("web")); + if ("missing".equals(outcome)) { + doThrow(new NotFoundException("already removed")).when(stop).exec(); + } else if ("stopped".equals(outcome)) { + doThrow(new NotModifiedException("already stopped")).when(stop).exec(); + } + InspectContainerCmd inspect = dockerClient.inspectContainerCmd("sidecar-id"); + InspectContainerResponse response = inspect.exec(); + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + doAnswer(invocation -> { + entered.countDown(); + release.await(); + return response; + }).when(inspect).exec(); + try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { + Future> stopped = executor.submit(() -> manager.stopTaskAndCollectExitCodes(handle)); + try { + assertTrue(entered.await(5, TimeUnit.SECONDS)); + assertTrue(manager.vpcForClient("172.17.0.5").isEmpty()); + assertTrue(manager.vpcForClient("2001:db8::5").isEmpty()); + } finally { + release.countDown(); + } + stopped.get(5, TimeUnit.SECONDS); + } + } + + @ParameterizedTest + @ValueSource(strings = {"success", "stopped", "failed", "grace"}) + void cleanupRevokesConfirmedStopBeforeRemovalButPreservesLiveGrace(String outcome) throws Exception { + dnsAttachments("sidecar-id", "172.17.0.5", "2001:db8::5"); + EcsTaskHandle handle = manager.startTask(taskWithEni(), + taskDefinition(NetworkMode.awsvpc, container("web", List.of())), List.of(), REGION); + ContainerLifecycleManager actualLifecycle = new ContainerLifecycleManager( + dockerClient, dockerClient, null, null, null); + when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean())) + .thenAnswer(invocation -> actualLifecycle.stopAndConfirmRemoved( + invocation.getArgument(0), invocation.getArgument(1), invocation.getArgument(2), + invocation.getArgument(3))); + when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean(), any())) + .thenAnswer(invocation -> actualLifecycle.stopAndConfirmRemoved( + invocation.getArgument(0), invocation.getArgument(1), invocation.getArgument(2), + invocation.getArgument(3), invocation.getArgument(4))); + StopContainerCmd stop = dockerClient.stopContainerCmd("sidecar-id").withTimeout(5); + RemoveContainerCmd remove = dockerClient.removeContainerCmd("sidecar-id").withForce(true); + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + if ("stopped".equals(outcome)) { + doThrow(new NotModifiedException("already stopped")).when(stop).exec(); + } else if ("failed".equals(outcome)) { + doThrow(new IllegalStateException("stop failed")).when(stop).exec(); + } + if ("grace".equals(outcome)) { + doAnswer(invocation -> { + entered.countDown(); + release.await(); + return null; + }).when(stop).exec(); + } else { + doAnswer(invocation -> { + entered.countDown(); + release.await(); + return null; + }).when(remove).exec(); + } + try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { + Future cleaned = executor.submit(() -> manager.cleanupStoppedTask(handle)); + try { + assertTrue(entered.await(5, TimeUnit.SECONDS)); + boolean stillLive = "failed".equals(outcome) || "grace".equals(outcome); + assertEquals(stillLive, manager.vpcForClient("172.17.0.5").isPresent()); + assertEquals(stillLive, manager.vpcForClient("2001:db8::5").isPresent()); + } finally { + release.countDown(); + } + cleaned.get(5, TimeUnit.SECONDS); + } + assertTrue(manager.vpcForClient("172.17.0.5").isEmpty()); + assertTrue(manager.vpcForClient("2001:db8::5").isEmpty()); + assertTrue(handle.allContainersRemoved()); + } + + @ParameterizedTest + @NullSource + @ValueSource(booleans = true) + void failedStopAndRemovalRetainLiveOriginUntilConfirmedCleanup(Boolean running) { + dnsAttachments("sidecar-id", "172.17.0.5", "2001:db8::5"); + EcsTask task = taskWithEni(); + EcsTaskHandle handle = manager.startTask(task, + taskDefinition(NetworkMode.awsvpc, container("web", List.of())), List.of(), REGION); + when(dockerClient.inspectContainerCmd("sidecar-id").exec().getState().getRunning()).thenReturn(running); + when(dockerClient.inspectContainerCmd("sidecar-id").exec().getState().getExitCodeLong()).thenReturn(null); + StopContainerCmd stop = dockerClient.stopContainerCmd("sidecar-id").withTimeout(handle.stopTimeoutFor("web")); + KillContainerCmd kill = dockerClient.killContainerCmd("sidecar-id"); + doThrow(new IllegalStateException("stop failed")).when(stop).exec(); + doThrow(new IllegalStateException("kill failed")).when(kill).exec(); + RemoveContainerCmd remove = dockerClient.removeContainerCmd("sidecar-id").withForce(true); + doThrow(new IllegalStateException("remove failed")).when(remove).exec(); + manager.stopTaskAndCollectExitCodes(handle); + manager.releaseTaskNetwork(task, REGION); + assertEquals(Optional.of(new ClientVpc("000000000000", REGION, "vpc-1")), + manager.vpcForClient("172.17.0.5")); + when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean(), any())).thenReturn(false); + manager.cleanupStoppedTask(handle); + assertTrue(manager.vpcForClient("172.17.0.5").isPresent()); + when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean(), any())).thenReturn(true); + manager.cleanupStoppedTask(handle); + assertTrue(manager.vpcForClient("172.17.0.5").isEmpty()); + } + + @Test + void stoppedAddressCanBeReusedBeforeItsSiblingStopsWithoutOldCleanupRemovingTheNewOwner() { + dnsAttachments("sidecar-id", "172.17.0.5", "2001:db8::5"); + dnsAttachments("web-id", "172.17.0.6", "2001:db8::6"); + dnsAttachments("replacement-id", "172.17.0.5", "2001:db8::5"); + EcsTaskHandle handle = manager.startTask(taskWithEni(), taskDefinition(NetworkMode.awsvpc, + container("sidecar", List.of()), container("web", List.of())), List.of(), REGION); + when(lifecycleManager.createAndStartEphemeral(any(), any())) + .thenReturn(new ContainerInfo("replacement-id", Map.of())); + ClientVpc replacementVpc = new ClientVpc("222222222222", REGION, "vpc-1"); + StopContainerCmd secondStop = dockerClient.stopContainerCmd("web-id") + .withTimeout(handle.stopTimeoutFor("web")); + doAnswer(invocation -> { + EcsTask replacement = taskWithEni(); + replacement.setTaskArn("arn:aws:ecs:us-east-1:222222222222:task/test-cluster/replacement"); + manager.startTask(replacement, taskDefinition(NetworkMode.awsvpc, container("web", List.of())), + List.of(), REGION); + assertEquals(Optional.of(replacementVpc), manager.vpcForClient("172.17.0.5")); + assertEquals(Optional.of(new ClientVpc("000000000000", REGION, "vpc-1")), + manager.vpcForClient("172.17.0.6")); + return null; + }).when(secondStop).exec(); + manager.stopTaskAndCollectExitCodes(handle); + assertEquals(Optional.of(replacementVpc), manager.vpcForClient("172.17.0.5")); + assertEquals(Optional.of(replacementVpc), manager.vpcForClient("2001:db8::5")); + assertTrue(manager.vpcForClient("172.17.0.6").isEmpty()); + } + + @Test + void confirmedStopRevokesOriginEvenWhenRemovalFails() { + dnsAttachments("sidecar-id", "172.17.0.5", "2001:db8::5"); + EcsTaskHandle handle = manager.startTask(taskWithEni(), + taskDefinition(NetworkMode.awsvpc, container("web", List.of())), List.of(), REGION); + RemoveContainerCmd remove = dockerClient.removeContainerCmd("sidecar-id").withForce(true); + doThrow(new IllegalStateException("remove failed")).when(remove).exec(); + manager.stopTaskAndCollectExitCodes(handle); + assertTrue(manager.vpcForClient("172.17.0.5").isEmpty()); + } + + @Test + void registeredHostLookupRequiresMatchingAccountRegionAndVpc() { + Instance instance = new Instance(); + instance.setOwnerId("111111111111"); + instance.setState(InstanceState.running()); + instance.setRegion(REGION); + instance.setVpcId("vpc-host"); + when(ec2Service.findInstanceForAccount("111111111111", REGION, "i-host")) + .thenReturn(Optional.of(instance)); + assertEquals(Optional.of(new ClientVpc("111111111111", REGION, "vpc-host")), + manager.vpcForInstance("111111111111", REGION, "i-host")); + assertTrue(manager.vpcForInstance("222222222222", REGION, "i-host").isEmpty()); + instance.setState(InstanceState.stopped()); + assertTrue(manager.vpcForInstance("111111111111", REGION, "i-host").isEmpty()); + instance.setState(InstanceState.running()); + instance.setRegion("us-west-2"); + assertTrue(manager.vpcForInstance("111111111111", REGION, "i-host").isEmpty()); + instance.setRegion(REGION); + instance.setVpcId(null); + assertTrue(manager.vpcForInstance("111111111111", REGION, "i-host").isEmpty()); + } + + @Test + void foreignHostContextCannotGiveATaskPrivateDnsAccess() { + dnsAttachments("sidecar-id", "172.17.0.5", "2001:db8::5"); + EcsTask task = taskWithEni(); + task.setNetworkInterfaceId(null); + manager.startTask(task, taskDefinition(NetworkMode.bridge, container("web", List.of())), List.of(), REGION, + new ClientVpc("222222222222", REGION, "vpc-host")); + assertTrue(manager.vpcForClient("172.17.0.5").isEmpty()); + } + + @Test + void awsvpcDnsUsesActualAttachmentsAndRevokesOnCleanup() { + dnsAttachments("sidecar-id", "172.17.0.5", "2001:db8::5"); + dnsAttachments("web-id", "172.17.0.6", "2001:db8::6"); + EcsTask task = taskWithEni(); + EcsTaskHandle handle = manager.startTask(task, taskDefinition(NetworkMode.awsvpc, + container("sidecar", List.of()), container("web", List.of())), List.of(), REGION); + ClientVpc expected = new ClientVpc("000000000000", REGION, "vpc-1"); + clearInvocations(dockerClient); + for (String address : List.of("172.17.0.5", "172.17.0.6", "2001:db8::5", "2001:db8::6")) { + assertEquals(Optional.of(expected), manager.vpcForClient(address)); + } + assertTrue(manager.vpcForClient("10.0.0.10").isEmpty(), "An ENI address is not proof of a Docker attachment"); + assertTrue(manager.vpcForClient(null).isEmpty()); + verifyNoInteractions(dockerClient); + manager.cleanupStoppedTask(handle); + assertTrue(manager.vpcForClient("172.17.0.5").isEmpty()); + assertTrue(manager.vpcForClient("2001:db8::6").isEmpty()); + } + + @Test + void failedLaunchRevokesAlreadyRegisteredDnsAddresses() { + dnsAttachments("sidecar-id", "172.17.0.5", "2001:db8::5"); + when(lifecycleManager.createAndStartEphemeral(any(), any())) + .thenReturn(new ContainerInfo("sidecar-id", Map.of())) + .thenThrow(new IllegalStateException("second container failed")); + assertThrows(RuntimeException.class, () -> manager.startTask(taskWithEni(), + taskDefinition(NetworkMode.awsvpc, container("sidecar", List.of()), container("web", List.of())), + List.of(), REGION)); + assertTrue(manager.vpcForClient("172.17.0.5").isEmpty()); + assertTrue(manager.vpcForClient("2001:db8::5").isEmpty()); + } + + @Test + void ambiguousTaskAddressDoesNotChooseAnotherVpcAndCleanupPreservesTheOtherTask() { + dnsAttachments("sidecar-id", "172.17.0.5", "2001:db8::5"); + dnsAttachments("web-id", "172.17.0.5", "2001:db8::5"); + EcsTask first = taskWithEni(); + EcsTaskHandle firstHandle = manager.startTask(first, + taskDefinition(NetworkMode.awsvpc, container("web", List.of())), List.of(), REGION); + EcsTask second = taskWithEni(); + second.setTaskArn("arn:aws:ecs:us-east-1:222222222222:task/test-cluster/second"); + EcsTaskHandle secondHandle = manager.startTask(second, + taskDefinition(NetworkMode.awsvpc, container("web", List.of())), List.of(), REGION); + assertTrue(manager.vpcForClient("172.17.0.5").isEmpty()); + manager.cleanupStoppedTask(firstHandle); + manager.releaseTaskNetwork(first, REGION); + assertEquals(Optional.of(new ClientVpc("222222222222", REGION, "vpc-1")), + manager.vpcForClient("172.17.0.5")); + manager.cleanupStoppedTask(secondHandle); + manager.releaseTaskNetwork(second, REGION); + assertTrue(manager.vpcForClient("172.17.0.5").isEmpty()); + } + + @ParameterizedTest + @ValueSource(strings = {"bridge", "host", "none"}) + void nonVpcNetworkDoesNotBorrowAnUnusedAwsvpcConfiguration(String mode) { + dnsAttachments("sidecar-id", "172.17.0.5", "2001:db8::5"); + manager.startTask(taskWithEni(), taskDefinition(NetworkMode.valueOf(mode), container("web", List.of())), + List.of(), REGION); + assertTrue(manager.vpcForClient("172.17.0.5").isEmpty()); + } + + private void dnsAttachments(String dockerId, String ipv4, String ipv6) { + InspectContainerResponse inspect = mock(InspectContainerResponse.class, RETURNS_DEEP_STUBS); + ContainerNetwork network = mock(ContainerNetwork.class); + when(network.getIpAddress()).thenReturn(ipv4); + when(network.getGlobalIPv6Address()).thenReturn(ipv6); + when(inspect.getNetworkSettings().getNetworks()).thenReturn(Map.of("floci-net", network)); + when(dockerClient.inspectContainerCmd(dockerId).exec()).thenReturn(inspect); + } + @Test void awsvpcTaskGivesItsEniAddressToTheFirstContainerThatMapsAPort() { manager.startTask(taskWithEni(), taskDefinition(NetworkMode.awsvpc, @@ -155,10 +494,15 @@ class EcsContainerManagerTaskAddressTest { EcsTask task = taskWithEni(); task.setNetworkInterfaceId(null); - manager.startTask(task, taskDefinition(NetworkMode.awsvpc, + EcsTaskHandle handle = manager.startTask(task, taskDefinition(NetworkMode.awsvpc, container("web", List.of(new PortMapping(80, 80, "tcp")))), List.of(), REGION); assertEquals("eni-1", task.getNetworkInterfaceId()); + assertEquals(Optional.of(new ClientVpc("000000000000", REGION, "vpc-1")), + manager.vpcForClient("10.0.0.5")); + manager.cleanupStoppedTask(handle); + manager.releaseTaskNetwork(task, REGION); + assertTrue(manager.vpcForClient("10.0.0.5").isEmpty()); verify(ec2Service, never()).attachContainerToVpc(any(), any(), any(), any(), any(), any()); } diff --git a/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerTaskRoleCredentialsTest.java b/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerTaskRoleCredentialsTest.java index c4ebd25f55..74a0503c32 100644 --- a/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerTaskRoleCredentialsTest.java +++ b/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerTaskRoleCredentialsTest.java @@ -79,7 +79,7 @@ class EcsContainerManagerTaskRoleCredentialsTest { ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class); // Its confirmed removal goes through the strict removal each test stubs. - when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean())).thenCallRealMethod(); + when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean(), any())).thenCallRealMethod(); when(lifecycleManager.resolveImageForLaunch(any(), any(), any())) .thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null)); when(lifecycleManager.createAndStartEphemeral(any(), any())).thenReturn(new ContainerInfo("docker-id", Map.of())); @@ -196,7 +196,7 @@ class EcsContainerManagerTaskRoleCredentialsTest { void revokesCredentialsEvenWhenAContainerCouldNotBeRemoved() { ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class); // Its confirmed removal goes through the strict removal each test stubs. - when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean())).thenCallRealMethod(); + when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean(), any())).thenCallRealMethod(); when(lifecycleManager.resolveImageForLaunch(any(), any(), any())) .thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null)); DockerClient dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS); @@ -243,7 +243,7 @@ class EcsContainerManagerTaskRoleCredentialsTest { void keepsAddressesReservedWhenAContainerCouldNotBeRemoved() { ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class); // Its confirmed removal goes through the strict removal each test stubs. - when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean())).thenCallRealMethod(); + when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean(), any())).thenCallRealMethod(); when(lifecycleManager.resolveImageForLaunch(any(), any(), any())) .thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null)); DockerClient dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS); @@ -269,14 +269,14 @@ class EcsContainerManagerTaskRoleCredentialsTest { void keepsAddressesReservedWhenCleanupCannotRemoveAContainer() { ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class); // Its confirmed removal goes through the strict removal each test stubs. - when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean())).thenCallRealMethod(); + when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean(), any())).thenCallRealMethod(); when(lifecycleManager.resolveImageForLaunch(any(), any(), any())) .thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null)); when(lifecycleManager.createAndStartEphemeral(any(), any())).thenReturn(new ContainerInfo("docker-id", Map.of())); // The reconciler's cleanup path is the other way a task's containers come off, and Docker // can refuse a removal here just as it can on the stop path. doThrow(new IllegalStateException("in use")) - .when(lifecycleManager).stopAndRemoveStrict("docker-id", null, 5, true); + .when(lifecycleManager).stopAndRemoveStrict(eq("docker-id"), any(), eq(5), eq(true), any()); EcsContainerManager stopping = new EcsContainerManager(containerBuilder, lifecycleManager, mock(ContainerLogStreamer.class), mock(ContainerDetector.class), config, mock(RegionResolver.class), baselineAwsEnv(), mock(SsmService.class), @@ -298,7 +298,7 @@ class EcsContainerManagerTaskRoleCredentialsTest { void keepsAddressesReservedWhenAFailedLaunchCannotRemoveAContainer() { ContainerLifecycleManager failing = mock(ContainerLifecycleManager.class); // Its confirmed removal goes through the strict removal each test stubs. - when(failing.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean())).thenCallRealMethod(); + when(failing.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean(), any())).thenCallRealMethod(); when(failing.resolveImageForLaunch(any(), any(), any())) .thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null)); // The first container starts and the second does not, so the launch unwinds with one @@ -307,7 +307,7 @@ class EcsContainerManagerTaskRoleCredentialsTest { .thenReturn(new ContainerInfo("docker-id", Map.of())) .thenThrow(new IllegalStateException("no daemon")); doThrow(new IllegalStateException("in use")) - .when(failing).stopAndRemoveStrict("docker-id", null, 5, true); + .when(failing).stopAndRemoveStrict(eq("docker-id"), any(), eq(5), eq(true), any()); EcsContainerManager failingManager = new EcsContainerManager(containerBuilder, failing, mock(ContainerLogStreamer.class), mock(ContainerDetector.class), config, mock(RegionResolver.class), baselineAwsEnv(), mock(SsmService.class), @@ -377,7 +377,7 @@ class EcsContainerManagerTaskRoleCredentialsTest { void revokesCredentialsWhenTheLaunchFailsPartWayThrough() { ContainerLifecycleManager failing = mock(ContainerLifecycleManager.class); // Its confirmed removal goes through the strict removal each test stubs. - when(failing.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean())).thenCallRealMethod(); + when(failing.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean(), any())).thenCallRealMethod(); when(failing.resolveImageForLaunch(any(), any(), any())) .thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null)); when(failing.createAndStartEphemeral(any(), any())).thenThrow(new IllegalStateException("no daemon")); diff --git a/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerVolumesTest.java b/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerVolumesTest.java index 2d8d054122..a92912a229 100644 --- a/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerVolumesTest.java +++ b/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerVolumesTest.java @@ -178,13 +178,13 @@ class EcsContainerManagerVolumesTest { ephemeralDefinition(new Volume("shared", null)), List.of(), "us-east-1"); String name = handle.getTaskVolumeNames().iterator().next(); doThrow(new IllegalStateException("remove failed")).when(lifecycleManager) - .stopAndRemoveStrict("docker-id", null, 5, true); + .stopAndRemoveStrict(eq("docker-id"), any(), eq(5), eq(true), any()); manager.cleanupStoppedTask(handle); assertTrue(handle.hasTaskVolumes()); verify(lifecycleManager, never()).removeVolume(name); - doNothing().when(lifecycleManager).stopAndRemoveStrict("docker-id", null, 5, true); + doNothing().when(lifecycleManager).stopAndRemoveStrict(eq("docker-id"), any(), eq(5), eq(true), any()); when(lifecycleManager.removeVolume(name)).thenReturn(true); manager.cleanupStoppedTask(handle); assertFalse(handle.hasTaskVolumes()); @@ -197,7 +197,7 @@ class EcsContainerManagerVolumesTest { .thenThrow(new IllegalStateException("launch failed")); if (containerRemovalFails) { doThrow(new IllegalStateException("remove failed")).when(lifecycleManager) - .stopAndRemoveStrict("docker-id", null, 5, true); + .stopAndRemoveStrict(eq("docker-id"), any(), eq(5), eq(true), any()); } else { when(lifecycleManager.removeVolume(anyString())).thenReturn(false); } @@ -209,7 +209,7 @@ class EcsContainerManagerVolumesTest { assertEquals(!containerRemovalFails, handle.allContainersRemoved()); assertEquals("launch failed", failure.getMessage()); - doNothing().when(lifecycleManager).stopAndRemoveStrict("docker-id", null, 5, true); + doNothing().when(lifecycleManager).stopAndRemoveStrict(eq("docker-id"), any(), eq(5), eq(true), any()); when(lifecycleManager.removeVolume(anyString())).thenReturn(true); manager.cleanupStoppedTask(handle); assertTrue(handle.allContainersRemoved()); @@ -261,7 +261,7 @@ class EcsContainerManagerVolumesTest { lifecycleManager = mock(ContainerLifecycleManager.class); // Its confirmed removal goes through the strict removal each test stubs. - when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean())).thenCallRealMethod(); + when(lifecycleManager.stopAndConfirmRemoved(any(), any(), anyInt(), anyBoolean(), any())).thenCallRealMethod(); when(lifecycleManager.removeVolume(anyString())).thenReturn(true); when(lifecycleManager.resolveImageForLaunch(any(), any(), any())) .thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null)); diff --git a/src/test/java/io/floci/aws/services/route53/Route53DnsResolutionTest.java b/src/test/java/io/floci/aws/services/route53/Route53DnsResolutionTest.java index 7129428a1b..09b72eb9c4 100644 --- a/src/test/java/io/floci/aws/services/route53/Route53DnsResolutionTest.java +++ b/src/test/java/io/floci/aws/services/route53/Route53DnsResolutionTest.java @@ -1,6 +1,8 @@ package io.floci.aws.services.route53; +import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.dns.DnsAnswer; +import io.floci.aws.core.common.dns.DnsClientVpcSource.ClientVpc; import io.floci.aws.core.common.dns.DnsLookupHelper; import io.floci.aws.core.common.dns.DnsRecord; import io.floci.aws.core.common.dns.EmbeddedDnsServer; @@ -36,6 +38,9 @@ class Route53DnsResolutionTest { @Inject Route53Service route53Service; + @Inject + EmulatorConfig config; + @InjectMock DnsLookupHelper dnsLookupHelper; @@ -72,7 +77,7 @@ class Route53DnsResolutionTest { String zoneId = createPrivateZone(zone); addRecord(zoneId, "api." + zone, "A", "10.0.1.100"); - Optional result = dnsRecordSource.resolveIpv4("api." + zone); + Optional result = resolveFromVpc("api." + zone); assertTrue(result.isPresent()); assertEquals(List.of("10.0.1.100"), result.get().addresses()); } @@ -83,7 +88,7 @@ class Route53DnsResolutionTest { String zoneId = createPrivateZone(zone); addRecord(zoneId, "api." + zone, "A", "10.0.1.100", 42L); - Optional result = dnsRecordSource.resolveIpv4("api." + zone); + Optional result = resolveFromVpc("api." + zone); assertTrue(result.isPresent()); assertEquals(42, result.get().ttlSeconds()); } @@ -96,7 +101,7 @@ class Route53DnsResolutionTest { addRecord(zoneId, "short." + zone, "CNAME", "api." + zone + ".", 30L); addRecord(zoneId, "long." + zone, "CNAME", "short." + zone + ".", 900L); - Optional result = dnsRecordSource.resolveIpv4("long." + zone); + Optional result = resolveFromVpc("long." + zone); assertTrue(result.isPresent()); assertEquals(List.of("10.0.3.50"), result.get().addresses()); assertEquals(30, result.get().ttlSeconds()); @@ -109,7 +114,7 @@ class Route53DnsResolutionTest { addRecord(zoneId, "target." + zone, "A", "10.0.4.99", 120L); addAlias(zoneId, "alias." + zone, "A", "target." + zone + "."); - Optional result = dnsRecordSource.resolveIpv4("alias." + zone); + Optional result = resolveFromVpc("alias." + zone); assertTrue(result.isPresent()); assertEquals(120, result.get().ttlSeconds()); } @@ -120,7 +125,7 @@ class Route53DnsResolutionTest { String zoneId = createPrivateZone(zone); addRecords(zoneId, "api." + zone, "A", List.of("10.0.1.101", "10.0.1.102")); - Optional result = dnsRecordSource.resolveIpv4("api." + zone); + Optional result = resolveFromVpc("api." + zone); assertTrue(result.isPresent()); assertEquals(2, result.get().addresses().size()); assertTrue(result.get().addresses().contains("10.0.1.101")); @@ -137,7 +142,7 @@ class Route53DnsResolutionTest { } addRecords(zoneId, "fleet." + zone, "A", ips); - Optional result = dnsRecordSource.resolveIpv4("fleet." + zone); + Optional result = resolveFromVpc("fleet." + zone); assertTrue(result.isPresent()); assertEquals(8, result.get().addresses().size()); } @@ -148,7 +153,7 @@ class Route53DnsResolutionTest { String zoneId = createPrivateZone(zone); addRecord(zoneId, "api." + zone, "A", "10.0.1.200"); - Optional result = dnsRecordSource.resolveIpv4("API." + zone.toUpperCase() + "."); + Optional result = resolveFromVpc("API." + zone.toUpperCase() + "."); assertTrue(result.isPresent()); assertEquals(List.of("10.0.1.200"), result.get().addresses()); } @@ -161,15 +166,15 @@ class Route53DnsResolutionTest { createdZoneIds.add(zoneId); addRecord(zoneId, "api." + zone, "A", "1.2.3.4"); - Optional result = dnsRecordSource.resolveIpv4("api." + zone); + Optional result = resolveFromVpc("api." + zone); assertTrue(result.isEmpty()); } @Test void doesNotResolveNameOutsideAnyPrivateZone() { - assertTrue(dnsRecordSource.resolveIpv4("example.com").isEmpty()); - assertTrue(dnsRecordSource.resolveIpv4("").isEmpty()); - assertTrue(dnsRecordSource.resolveIpv4(null).isEmpty()); + assertTrue(resolveFromVpc("example.com").isEmpty()); + assertTrue(resolveFromVpc("").isEmpty()); + assertTrue(resolveFromVpc(null).isEmpty()); } @Test @@ -178,7 +183,7 @@ class Route53DnsResolutionTest { String zoneId = createPrivateZone(zone); addRecord(zoneId, "*." + zone, "A", "10.0.2.1"); - Optional result = dnsRecordSource.resolveIpv4("app." + zone); + Optional result = resolveFromVpc("app." + zone); assertTrue(result.isPresent()); assertEquals(List.of("10.0.2.1"), result.get().addresses()); } @@ -191,7 +196,7 @@ class Route53DnsResolutionTest { addRecord(zoneId, "b." + zone, "TXT", "\"text-record\""); // Wildcard should not match a.b.zone because b.zone exists - Optional result = dnsRecordSource.resolveIpv4("a.b." + zone); + Optional result = resolveFromVpc("a.b." + zone); assertTrue(result.isPresent()); assertEquals(DnsAnswer.nxDomain(), result.get()); } @@ -203,16 +208,16 @@ class Route53DnsResolutionTest { addRecord(zoneId, "*." + zone, "A", "10.0.2.1"); addRecord(zoneId, "api.team." + zone, "A", "10.0.2.2"); - Optional team = dnsRecordSource.resolveIpv4("team." + zone); + Optional team = resolveFromVpc("team." + zone); assertTrue(team.isPresent()); assertTrue(team.get().isEmpty()); assertTrue(team.get().nameExists()); - Optional web = dnsRecordSource.resolveIpv4("web.team." + zone); + Optional web = resolveFromVpc("web.team." + zone); assertTrue(web.isPresent()); assertEquals(DnsAnswer.nxDomain(), web.get()); - Optional other = dnsRecordSource.resolveIpv4("other." + zone); + Optional other = resolveFromVpc("other." + zone); assertTrue(other.isPresent()); assertEquals(List.of("10.0.2.1"), other.get().addresses()); } @@ -224,7 +229,7 @@ class Route53DnsResolutionTest { addRecord(zoneId, "*." + zone, "A", "10.0.2.1"); addRecord(zoneId, "*.team." + zone, "A", "10.0.2.3"); - Optional result = dnsRecordSource.resolveIpv4("web.team." + zone); + Optional result = resolveFromVpc("web.team." + zone); assertTrue(result.isPresent()); assertEquals(List.of("10.0.2.3"), result.get().addresses()); } @@ -236,7 +241,7 @@ class Route53DnsResolutionTest { addRecord(zoneId, "api." + zone, "A", "10.0.3.50"); addRecord(zoneId, "service." + zone, "CNAME", "api." + zone + "."); - Optional result = dnsRecordSource.resolveIpv4("service." + zone); + Optional result = resolveFromVpc("service." + zone); assertTrue(result.isPresent()); assertEquals(List.of("10.0.3.50"), result.get().addresses()); } @@ -248,7 +253,7 @@ class Route53DnsResolutionTest { addRecord(zoneId, "cname1." + zone, "CNAME", "cname2." + zone); addRecord(zoneId, "cname2." + zone, "CNAME", "cname1." + zone); - Optional result = dnsRecordSource.resolveIpv4("cname1." + zone); + Optional result = resolveFromVpc("cname1." + zone); assertTrue(result.isPresent()); assertEquals(List.of(), result.get().addresses()); } @@ -259,7 +264,7 @@ class Route53DnsResolutionTest { String zoneId = createPrivateZone(zone); addRecord(zoneId, "ec2host." + zone, "CNAME", "ip-10-0-5-88.ec2.internal."); - Optional result = dnsRecordSource.resolveIpv4("ec2host." + zone); + Optional result = resolveFromVpc("ec2host." + zone); assertTrue(result.isPresent()); assertEquals(List.of("10.0.5.88"), result.get().addresses()); } @@ -273,7 +278,7 @@ class Route53DnsResolutionTest { String zoneId = createPrivateZone(zone); addRecord(zoneId, "ext." + zone, "CNAME", "external.example.com."); - Optional result = dnsRecordSource.resolveIpv4("ext." + zone); + Optional result = resolveFromVpc("ext." + zone); assertTrue(result.isPresent()); assertEquals(List.of("93.184.216.34"), result.get().addresses()); } @@ -285,7 +290,7 @@ class Route53DnsResolutionTest { addRecord(zoneId, "target." + zone, "A", "10.0.4.99"); addAlias(zoneId, "alias." + zone, "A", "target." + zone + "."); - Optional result = dnsRecordSource.resolveIpv4("alias." + zone); + Optional result = resolveFromVpc("alias." + zone); assertTrue(result.isPresent()); assertEquals(List.of("10.0.4.99"), result.get().addresses()); } @@ -295,7 +300,7 @@ class Route53DnsResolutionTest { String zone = uniqueZone(); createPrivateZone(zone); - Optional result = dnsRecordSource.resolveIpv4("nonexistent." + zone); + Optional result = resolveFromVpc("nonexistent." + zone); assertTrue(result.isPresent()); assertEquals(DnsAnswer.nxDomain(), result.get()); } @@ -306,7 +311,7 @@ class Route53DnsResolutionTest { String zoneId = createPrivateZone(zone); addRecord(zoneId, "api.team." + zone, "A", "10.0.6.1"); - Optional result = dnsRecordSource.resolveIpv4("team." + zone); + Optional result = resolveFromVpc("team." + zone); assertTrue(result.isPresent()); assertTrue(result.get().isEmpty()); assertTrue(result.get().nameExists()); @@ -321,7 +326,7 @@ class Route53DnsResolutionTest { String zoneId = createPrivateZone(zone); addRecord(zoneId, "ext." + zone, "CNAME", "external-ttl.example.com.", 3600L); - Optional result = dnsRecordSource.resolveIpv4("ext." + zone); + Optional result = resolveFromVpc("ext." + zone); assertTrue(result.isPresent()); assertEquals(List.of("93.184.216.35"), result.get().addresses()); assertEquals(DnsAnswer.DEFAULT_TTL_SECONDS, result.get().ttlSeconds()); @@ -333,7 +338,7 @@ class Route53DnsResolutionTest { String zoneId = createPrivateZone(zone); addRecord(zoneId, "txtonly." + zone, "TXT", "\"only text here\""); - Optional result = dnsRecordSource.resolveIpv4("txtonly." + zone); + Optional result = resolveFromVpc("txtonly." + zone); assertTrue(result.isPresent()); assertTrue(result.get().isEmpty()); assertTrue(result.get().nameExists()); @@ -349,7 +354,7 @@ class Route53DnsResolutionTest { addRecord(parentId, "api.sub." + parentZone, "A", "10.0.10.1"); addRecord(childId, "api." + childZone, "A", "10.0.20.1"); - Optional result = dnsRecordSource.resolveIpv4("api.sub." + parentZone); + Optional result = resolveFromVpc("api.sub." + parentZone); assertTrue(result.isPresent()); assertEquals(List.of("10.0.20.1"), result.get().addresses()); } @@ -360,19 +365,31 @@ class Route53DnsResolutionTest { String zoneId = createPrivateZone(zone); addRecord(zoneId, "floci-cname." + zone, "CNAME", "s3.localhost.localstack.cloud"); - Optional result = dnsRecordSource.resolveIpv4("floci-cname." + zone); + Optional result = resolveFromVpc("floci-cname." + zone); assertTrue(result.isPresent()); String expectedIp = InetAddress.getLocalHost().getHostAddress(); assertEquals(List.of(expectedIp), result.get().addresses()); } + @Test + void privateCnameToEmulatorSuffixUsesTheAdvertisedDnsAddress() { + Mockito.when(embeddedDnsServer.getServerIp()).thenReturn(Optional.of("172.26.0.2")); + String zone = uniqueZone(); + String zoneId = createPrivateZone(zone); + addRecord(zoneId, "service." + zone, "CNAME", "s3.localhost.floci.io"); + + Optional result = resolveFromVpc("service." + zone); + assertTrue(result.isPresent()); + assertEquals(List.of("172.26.0.2"), result.get().addresses()); + } + @Test void cnameTargetToDefaultFlociSuffixResolvesLocalAddress() throws Exception { String zone = uniqueZone(); String zoneId = createPrivateZone(zone); addRecord(zoneId, "floci-cname2." + zone, "CNAME", "sqs.localhost.floci.io"); - Optional result = dnsRecordSource.resolveIpv4("floci-cname2." + zone); + Optional result = resolveFromVpc("floci-cname2." + zone); assertTrue(result.isPresent()); String expectedIp = InetAddress.getLocalHost().getHostAddress(); assertEquals(List.of(expectedIp), result.get().addresses()); @@ -384,7 +401,7 @@ class Route53DnsResolutionTest { String zoneId = createPrivateZone(zone); addAlias(zoneId, "floci-alias." + zone, "A", "s3.localhost.localstack.cloud"); - Optional result = dnsRecordSource.resolveIpv4("floci-alias." + zone); + Optional result = resolveFromVpc("floci-alias." + zone); assertTrue(result.isPresent()); String expectedIp = InetAddress.getLocalHost().getHostAddress(); assertEquals(List.of(expectedIp), result.get().addresses()); @@ -400,9 +417,9 @@ class Route53DnsResolutionTest { addAlias(zoneId, "floci-alias." + zone, "A", "s3.localhost.localstack.cloud"); assertEquals(List.of("172.19.0.2"), - dnsRecordSource.resolveIpv4("floci-cname." + zone).orElseThrow().addresses()); + resolveFromVpc("floci-cname." + zone).orElseThrow().addresses()); assertEquals(List.of("172.19.0.2"), - dnsRecordSource.resolveIpv4("floci-alias." + zone).orElseThrow().addresses()); + resolveFromVpc("floci-alias." + zone).orElseThrow().addresses()); } @Test @@ -414,7 +431,7 @@ class Route53DnsResolutionTest { String zoneId = createPrivateZone(zone); addAlias(zoneId, "bare-alias." + zone, "A", "s3.localstack.cloud"); - Optional result = dnsRecordSource.resolveIpv4("bare-alias." + zone); + Optional result = resolveFromVpc("bare-alias." + zone); assertTrue(result.isPresent()); String localIp = InetAddress.getLocalHost().getHostAddress(); assertFalse(result.get().addresses().contains(localIp)); @@ -427,7 +444,7 @@ class Route53DnsResolutionTest { String zoneId = createPrivateZone(zone); addAlias(zoneId, "ec2-alias." + zone, "A", "ip-10-0-0-5.ec2.internal"); - Optional result = dnsRecordSource.resolveIpv4("ec2-alias." + zone); + Optional result = resolveFromVpc("ec2-alias." + zone); assertTrue(result.isPresent()); assertEquals(List.of("10.0.0.5"), result.get().addresses()); } @@ -438,12 +455,12 @@ class Route53DnsResolutionTest { String id = createPrivateZone(zone); String name = "_api._tcp." + zone; addRecord(id, name, "SRV", " \t65535\t 65535 65535\tTarget." + zone + ". \t", 0L); - DnsAnswer answer = dnsRecordSource.resolve(name.toUpperCase() + ".", 33).orElseThrow(); + DnsAnswer answer = dnsRecordSource.resolve(name.toUpperCase() + ".", 33, new ClientVpc(config.defaultAccountId(), "us-east-1", "vpc-12345")).orElseThrow(); assertEquals(0, answer.ttlSeconds()); assertEquals(List.of(new DnsRecord.Srv(65535, 65535, 65535, "Target." + zone + ".")), answer.records()); addRecord(id, "_unavailable._tcp." + zone, "SRV", "0 0 0 ."); assertEquals(List.of(new DnsRecord.Srv(0, 0, 0, ".")), - dnsRecordSource.resolve("_unavailable._tcp." + zone, 33).orElseThrow().records()); + dnsRecordSource.resolve("_unavailable._tcp." + zone, 33, new ClientVpc(config.defaultAccountId(), "us-east-1", "vpc-12345")).orElseThrow().records()); } @ParameterizedTest @@ -459,7 +476,7 @@ class Route53DnsResolutionTest { set.setRecords(List.of(new ResourceRecord("0 0 8080 target." + zone))); route53Service.changeResourceRecordSets(id, List.of(Map.of("action", "CREATE", "rrs", set)), null); - DnsAnswer answer = dnsRecordSource.resolve(name, 33).orElseThrow(); + DnsAnswer answer = dnsRecordSource.resolve(name, 33, new ClientVpc(config.defaultAccountId(), "us-east-1", "vpc-12345")).orElseThrow(); assertEquals(0, answer.responseCode()); assertEquals(expectedTtl, answer.ttlSeconds()); assertEquals(List.of(new DnsRecord.Srv(0, 0, 8080, "target." + zone)), answer.records()); @@ -479,7 +496,7 @@ class Route53DnsResolutionTest { values.add("0 100 8080 valid." + zone); values.add(value); addRecords(id, name, "SRV", values); - DnsAnswer answer = dnsRecordSource.resolve(name, 33).orElseThrow(); + DnsAnswer answer = dnsRecordSource.resolve(name, 33, new ClientVpc(config.defaultAccountId(), "us-east-1", "vpc-12345")).orElseThrow(); assertEquals(5, answer.responseCode()); assertTrue(answer.isEmpty()); Mockito.verifyNoInteractions(dnsLookupHelper); @@ -490,10 +507,10 @@ class Route53DnsResolutionTest { String zone = uniqueZone(); String id = createPrivateZone(zone); addRecord(id, "address." + zone, "A", "192.0.2.1"); - assertEquals(DnsAnswer.noData(), dnsRecordSource.resolve("address." + zone, 33).orElseThrow()); - assertEquals(DnsAnswer.noData(), dnsRecordSource.resolve(zone, 33).orElseThrow()); - assertEquals(DnsAnswer.nxDomain(), dnsRecordSource.resolve("absent." + zone, 33).orElseThrow()); - assertEquals(List.of("192.0.2.1"), dnsRecordSource.resolve("address." + zone, 1).orElseThrow().addresses()); + assertEquals(DnsAnswer.noData(), dnsRecordSource.resolve("address." + zone, 33, new ClientVpc(config.defaultAccountId(), "us-east-1", "vpc-12345")).orElseThrow()); + assertEquals(DnsAnswer.noData(), dnsRecordSource.resolve(zone, 33, new ClientVpc(config.defaultAccountId(), "us-east-1", "vpc-12345")).orElseThrow()); + assertEquals(DnsAnswer.nxDomain(), dnsRecordSource.resolve("absent." + zone, 33, new ClientVpc(config.defaultAccountId(), "us-east-1", "vpc-12345")).orElseThrow()); + assertEquals(List.of("192.0.2.1"), dnsRecordSource.resolve("address." + zone, 1, new ClientVpc(config.defaultAccountId(), "us-east-1", "vpc-12345")).orElseThrow().addresses()); String publicZone = uniqueZone(); String publicId = route53Service.createHostedZone(publicZone, UUID.randomUUID().toString(), @@ -501,10 +518,10 @@ class Route53DnsResolutionTest { createdZoneIds.add(publicId); String publicName = "_api._tcp." + publicZone; addRecord(publicId, publicName, "SRV", "0 100 8080 target." + publicZone); - assertTrue(dnsRecordSource.resolve(publicName, 33).isEmpty()); + assertTrue(dnsRecordSource.resolve(publicName, 33, new ClientVpc(config.defaultAccountId(), "us-east-1", "vpc-12345")).isEmpty()); assertTrue(dnsRecordSource.resolveAuthoritative(publicName, 33).isEmpty()); - assertTrue(dnsRecordSource.resolve(null, 33).isEmpty()); - assertTrue(dnsRecordSource.resolve(" ", 33).isEmpty()); + assertTrue(dnsRecordSource.resolve(null, 33, new ClientVpc(config.defaultAccountId(), "us-east-1", "vpc-12345")).isEmpty()); + assertTrue(dnsRecordSource.resolve(" ", 33, new ClientVpc(config.defaultAccountId(), "us-east-1", "vpc-12345")).isEmpty()); Mockito.verifyNoInteractions(dnsLookupHelper); } @@ -520,16 +537,56 @@ class Route53DnsResolutionTest { set.setWeight(100L); set.setRecords(List.of(new ResourceRecord("0 100 8080 target." + zone))); route53Service.changeResourceRecordSets(id, List.of(Map.of("action", "CREATE", "rrs", set)), null); - assertEquals(5, dnsRecordSource.resolve(set.getName(), 33).orElseThrow().responseCode()); + assertEquals(5, dnsRecordSource.resolve(set.getName(), 33, new ClientVpc(config.defaultAccountId(), "us-east-1", "vpc-12345")).orElseThrow().responseCode()); + } + + @Test + void unknownCallerRetainsPrivateRecords() { + String zone = uniqueZone(); + String id = createPrivateZone(zone); + addRecord(id, "api." + zone, "A", "10.0.1.100"); + addRecord(id, "leaf.branch." + zone, "A", "10.0.1.101"); + + assertEquals(List.of("10.0.1.100"), dnsRecordSource.resolveIpv4("api." + zone).map(DnsAnswer::addresses).orElse(List.of())); + assertEquals(List.of("10.0.1.100"), dnsRecordSource.resolve("api." + zone, 1, null).orElseThrow().addresses()); + assertEquals(DnsAnswer.noData(), dnsRecordSource.resolve("api." + zone, 28, null).orElseThrow()); + assertEquals(DnsAnswer.noData(), dnsRecordSource.resolve("branch." + zone, 1, null).orElseThrow()); + assertEquals(DnsAnswer.nxDomain(), dnsRecordSource.resolve("absent." + zone, 1, null).orElseThrow()); + } + + @ParameterizedTest + @ValueSource(strings = {"CNAME", "ALIAS"}) + void chasingTargetsKeepsTheOriginalVpcVisibility(String type) { + String sourceName = uniqueZone(); + String targetName = "api." + uniqueZone(); + String sourceZone = createPrivateZone(sourceName); + addRecord(createPrivateZone(targetName, "vpc-54321"), targetName, "A", "10.99.1.7"); + Mockito.when(dnsLookupHelper.resolveIpv4(targetName)).thenReturn(List.of("203.0.113.7")); + if ("CNAME".equals(type)) { + addRecord(sourceZone, "alias." + sourceName, "CNAME", targetName); + } else { + addAlias(sourceZone, "alias." + sourceName, "A", targetName); + } + + assertEquals(List.of("203.0.113.7"), resolveFromVpc("alias." + sourceName).orElseThrow().addresses()); + Mockito.verify(dnsLookupHelper).resolveIpv4(targetName); + } + + private Optional resolveFromVpc(String name) { + return dnsRecordSource.resolve(name, 1, new ClientVpc(config.defaultAccountId(), "us-east-1", "vpc-12345")); } private String createPrivateZone(String name) { + return createPrivateZone(name, "vpc-12345"); + } + + private String createPrivateZone(String name, String vpcId) { String zoneName = name.endsWith(".") ? name : name + "."; String id = route53Service.createHostedZone( zoneName, UUID.randomUUID().toString(), "test private zone", - new VpcAssociation("vpc-12345", "us-east-1")).zone().getId(); + new VpcAssociation(vpcId, "us-east-1")).zone().getId(); createdZoneIds.add(id); return id; } diff --git a/src/test/java/io/floci/aws/services/route53/Route53ServiceTest.java b/src/test/java/io/floci/aws/services/route53/Route53ServiceTest.java index a04d3749b5..137c87d33f 100644 --- a/src/test/java/io/floci/aws/services/route53/Route53ServiceTest.java +++ b/src/test/java/io/floci/aws/services/route53/Route53ServiceTest.java @@ -673,12 +673,12 @@ class Route53ServiceTest { service.changeResourceRecordSets(zoneId, List.of(change("CREATE", aRecord("app.corp.internal.", 300, "10.0.0.1"))), null); - List beforeClear = service.findPrivateRecordsForName("app.corp.internal."); + List beforeClear = service.findPrivateRecordsForName("app.corp.internal.", null); assertThat(beforeClear, hasSize(1)); service.clear(); - List afterClear = service.findPrivateRecordsForName("app.corp.internal."); + List afterClear = service.findPrivateRecordsForName("app.corp.internal.", null); assertThat(afterClear, empty()); } @@ -689,12 +689,12 @@ class Route53ServiceTest { new VpcAssociation("vpc-123", "us-east-1")); service.createHostedZone("public.com.", "ref-public", null, null); - assertTrue(service.isCoveredByPrivateZone("corp.internal")); - assertTrue(service.isCoveredByPrivateZone("app.corp.internal.")); - assertTrue(service.isCoveredByPrivateZone("sub.service.corp.internal")); - assertFalse(service.isCoveredByPrivateZone("public.com")); - assertFalse(service.isCoveredByPrivateZone("othercorp.internal")); - assertFalse(service.isCoveredByPrivateZone("example.org")); + assertTrue(service.isCoveredByPrivateZone("corp.internal", null)); + assertTrue(service.isCoveredByPrivateZone("app.corp.internal.", null)); + assertTrue(service.isCoveredByPrivateZone("sub.service.corp.internal", null)); + assertFalse(service.isCoveredByPrivateZone("public.com", null)); + assertFalse(service.isCoveredByPrivateZone("othercorp.internal", null)); + assertFalse(service.isCoveredByPrivateZone("example.org", null)); } private static HealthCheckConfig httpsCheck(String path) {