mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(route53): support reusable delegation sets (#7020)
* feat(route53): add reusable delegation set APIs * feat(route53): associate reusable delegation sets with hosted zones * fix(route53): preserve delegation ownership and assignments * fix(route53): authorize delegation set operations by matched route * fix(route53): filter hosted zones by reusable delegation set * fix(iam): select REST XML denials from the service catalog * perf(test): reuse Route53 IAM enforcement fixtures
This commit is contained in:
1 parent
a2e12ee004
commit
7f785fdc4c
17 files changed
+1343
-34
No files matched your search
@@ -149,6 +149,31 @@ class IamEnforcementFilterTest {
|
||||
catalog, scpProvider, sessionAccountLookup, null, null, clock, resourceInfo);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"aws-cn,GetReusableDelegationSet", "aws-cn,DeleteReusableDelegationSet",
|
||||
"aws-us-gov,GetReusableDelegationSet", "aws-us-gov,DeleteReusableDelegationSet"})
|
||||
void delegationSetAuthorizationKeepsTheRequestPartitionForAnUnknownRegion(String partition, String operation) {
|
||||
ContainerRequestContext request = mock(ContainerRequestContext.class);
|
||||
String action = "route53:" + operation;
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=ASIASESSION/20260629/future-1/route53/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
requestContext.setAccountId("222233334444");
|
||||
requestContext.setRegion("future-1");
|
||||
requestContext.setPartition(partition);
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIASESSION");
|
||||
when(request.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("route53", request)).thenReturn(action);
|
||||
when(iamService.resolveCallerContext(eq("ASIASESSION"), any())).thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"route53:*","Resource":"*"}]}
|
||||
""")));
|
||||
when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), eq(action), any(), isNull()))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
|
||||
|
||||
newFilter().filter(request);
|
||||
|
||||
verify(arnBuilder).buildResources("route53", action, request, "future-1", "222233334444", partition);
|
||||
}
|
||||
|
||||
@Test
|
||||
void filterBuildsResourceArnWithRequestContextAccount() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
@@ -2050,6 +2075,31 @@ class IamEnforcementFilterTest {
|
||||
assertTrue(body.contains("<RequestId>"), body);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"REST_XML, application/xml", "REST_JSON, application/json"})
|
||||
void restDenialUsesTheServiceCatalogProtocol(ServiceProtocol serviceProtocol, String expectedContentType) {
|
||||
ContainerRequestContext request = mock(ContainerRequestContext.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=AKIAUSER/20261030/us-east-1/catalog-service/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
ServiceDescriptor descriptor = descriptor("catalog-service", serviceProtocol, Set.of("catalog-service"), null);
|
||||
requestContext.setAccountId("000000000000");
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIAUSER");
|
||||
when(request.getHeaderString("Authorization")).thenReturn(auth);
|
||||
stubClaim(request, WireProtocol.REST, descriptor);
|
||||
when(catalog.byCredentialScope("catalog-service")).thenReturn(Optional.of(descriptor));
|
||||
when(actionRegistry.resolveRoute("catalog-service", request)).thenReturn("catalog-service:Read");
|
||||
when(iamService.resolveCallerContext(eq("AKIAUSER"), any())).thenReturn(CallerContext.of(List.of()));
|
||||
when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), eq("catalog-service:Read"), any(), any()))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.DENY);
|
||||
|
||||
newFilter().filter(request);
|
||||
|
||||
ArgumentCaptor<Response> response = ArgumentCaptor.captor();
|
||||
verify(request).abortWith(response.capture());
|
||||
assertEquals(403, response.getValue().getStatus());
|
||||
assertEquals(MediaType.valueOf(expectedContentType), response.getValue().getMediaType());
|
||||
}
|
||||
|
||||
/**
|
||||
* SNS refuses with its own {@code AuthorizationError}, the 403 every SNS operation lists, whichever action is
|
||||
* denied (a role it is passed as well as its own); another Query service still answers {@code AccessDenied}.
|
||||
|
||||
@@ -3,7 +3,9 @@ package io.github.hectorvent.floci.services.iam;
|
||||
import io.github.hectorvent.floci.core.common.AwsProtocolClaimFilter;
|
||||
import io.github.hectorvent.floci.core.common.ProtocolClaim;
|
||||
import io.github.hectorvent.floci.core.common.WireProtocol;
|
||||
import io.github.hectorvent.floci.services.route53.Route53Controller;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.container.ResourceInfo;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
@@ -18,6 +20,7 @@ import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
@@ -38,6 +41,20 @@ class IamActionRegistryTest {
|
||||
|
||||
private final IamActionRegistry registry = new IamActionRegistry();
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"createReusableDelegationSet,CreateReusableDelegationSet",
|
||||
"getReusableDelegationSet,GetReusableDelegationSet",
|
||||
"listReusableDelegationSets,ListReusableDelegationSets",
|
||||
"deleteReusableDelegationSet,DeleteReusableDelegationSet"})
|
||||
void matchedDelegationSetMethodsResolveTheirOwnActions(String method, String operation) {
|
||||
ResourceInfo info = Mockito.mock(ResourceInfo.class);
|
||||
Mockito.doReturn(Route53Controller.class).when(info).getResourceClass();
|
||||
when(info.getResourceMethod()).thenReturn(Arrays.stream(Route53Controller.class.getMethods())
|
||||
.filter(candidate -> candidate.getName().equals(method)).findFirst().orElseThrow());
|
||||
assertEquals("route53:" + operation, registry.resolveMatchedRoute("route53", info));
|
||||
assertNull(registry.resolveMatchedRoute("s3", info));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"PUT,PutProvisionedConcurrencyConfig", "GET,GetProvisionedConcurrencyConfig",
|
||||
"DELETE,DeleteProvisionedConcurrencyConfig"})
|
||||
|
||||
@@ -24,6 +24,8 @@ import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
@@ -55,6 +57,22 @@ class ResourceArnBuilderTest {
|
||||
private MultivaluedMap<String, String> queryParams;
|
||||
private Map<String, Object> contextProperties;
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"aws,us-east-1", "aws-us-gov,us-gov-west-1", "aws-cn,cn-north-1"})
|
||||
void delegationSetResourcesAreGlobalAndUseTheDecodedId(String partition, String region) {
|
||||
for (String id : List.of("N1", "%2Fdelegationset%2FN1")) {
|
||||
when(uriInfo.getRequestUri()).thenReturn(URI.create("http://localhost/2013-04-01/delegationset/" + id));
|
||||
when(uriInfo.getBaseUri()).thenReturn(URI.create("http://localhost/"));
|
||||
MultivaluedMap<String, String> parameters = new MultivaluedHashMap<>();
|
||||
parameters.putSingle("Id", id.equals("N1") ? "N1" : "/delegationset/N1");
|
||||
when(uriInfo.getPathParameters()).thenReturn(parameters);
|
||||
for (String operation : List.of("GetReusableDelegationSet", "DeleteReusableDelegationSet")) {
|
||||
assertEquals(List.of("arn:" + partition + ":route53:::delegationset/N1"),
|
||||
builder.buildResources("route53", "route53:" + operation, ctx, region, ACCOUNT, partition));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
builder = new ResourceArnBuilder(new ObjectMapper());
|
||||
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
package io.github.hectorvent.floci.services.route53;
|
||||
|
||||
import io.github.hectorvent.floci.testing.AwsTestClients;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.route53.Route53Client;
|
||||
import software.amazon.awssdk.services.route53.model.CreateHostedZoneResponse;
|
||||
import software.amazon.awssdk.services.route53.model.DelegationSet;
|
||||
import software.amazon.awssdk.services.route53.model.ListHostedZonesResponse;
|
||||
import software.amazon.awssdk.services.route53.model.RRType;
|
||||
import software.amazon.awssdk.services.route53.model.ResourceRecord;
|
||||
import software.amazon.awssdk.services.route53.model.ResourceRecordSet;
|
||||
import software.amazon.awssdk.services.route53.model.Route53Exception;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class Route53DelegationSetHostedZonesIntegrationTest {
|
||||
@Test
|
||||
void zonesReuseTheSetInResponsesAndApexRecordsUntilAllZonesAreDeleted() {
|
||||
try (Route53Client client = client("741686000010")) {
|
||||
DelegationSet set = createSet(client);
|
||||
String first = createZone(client, "first.example.", set.id()).hostedZone().id();
|
||||
String second = createZone(client, "second.example.", set.id()).hostedZone().id();
|
||||
String firstZone = first;
|
||||
try {
|
||||
assertEquals(set, client.getHostedZone(r -> r.id(firstZone)).delegationSet());
|
||||
assertEquals(set, client.getHostedZone(r -> r.id(second)).delegationSet());
|
||||
List<ResourceRecordSet> records = client.listResourceRecordSets(r -> r.hostedZoneId(firstZone))
|
||||
.resourceRecordSets();
|
||||
assertEquals(set.nameServers().stream().map(ns -> ns + ".").sorted().toList(), records.stream()
|
||||
.filter(r -> r.type() == RRType.NS).flatMap(r -> r.resourceRecords().stream())
|
||||
.map(ResourceRecord::value).sorted().toList());
|
||||
assertTrue(records.stream().filter(r -> r.type() == RRType.SOA).findFirst().orElseThrow()
|
||||
.resourceRecords().getFirst().value().startsWith(set.nameServers().getFirst() + ". "));
|
||||
assertError("DelegationSetInUse", () -> client.deleteReusableDelegationSet(r -> r.id(set.id())));
|
||||
client.deleteHostedZone(r -> r.id(firstZone));
|
||||
first = null;
|
||||
assertError("DelegationSetInUse", () -> client.deleteReusableDelegationSet(r -> r.id(set.id())));
|
||||
} finally {
|
||||
if (first != null) {
|
||||
String remaining = first;
|
||||
client.deleteHostedZone(r -> r.id(remaining));
|
||||
}
|
||||
client.deleteHostedZone(r -> r.id(second));
|
||||
client.deleteReusableDelegationSet(r -> r.id(set.id()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createHostedZoneReturnsTheSelectedDelegationSet() {
|
||||
try (Route53Client client = client("741686000011")) {
|
||||
DelegationSet set = createSet(client);
|
||||
CreateHostedZoneResponse zone = createZone(client, "created.example.", set.id());
|
||||
try {
|
||||
assertEquals(set, zone.delegationSet());
|
||||
} finally {
|
||||
client.deleteHostedZone(r -> r.id(zone.hostedZone().id()));
|
||||
client.deleteReusableDelegationSet(r -> r.id(set.id()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExistingPublicZoneCanBePromotedOnlyOnceAndRemainsInUse() {
|
||||
try (Route53Client client = client("741686000012")) {
|
||||
CreateHostedZoneResponse zone = createZone(client, "promoted.example.", null);
|
||||
String reference = UUID.randomUUID().toString();
|
||||
DelegationSet set = client.createReusableDelegationSet(r ->
|
||||
r.callerReference(reference).hostedZoneId(zone.hostedZone().id())).delegationSet();
|
||||
try {
|
||||
assertEquals(zone.delegationSet().nameServers(), set.nameServers());
|
||||
assertEquals(reference, set.callerReference());
|
||||
assertEquals(set, client.getHostedZone(r -> r.id(zone.hostedZone().id())).delegationSet());
|
||||
assertError("DelegationSetAlreadyReusable", () -> client.createReusableDelegationSet(r ->
|
||||
r.callerReference(UUID.randomUUID().toString()).hostedZoneId(zone.hostedZone().id())));
|
||||
assertError("DelegationSetInUse", () -> client.deleteReusableDelegationSet(r -> r.id(set.id())));
|
||||
} finally {
|
||||
client.deleteHostedZone(r -> r.id(zone.hostedZone().id()));
|
||||
client.deleteReusableDelegationSet(r -> r.id(set.id()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void relatedPublicNamesCannotShareNameServersButSiblingDomainsCan() {
|
||||
try (Route53Client client = client("741686000013")) {
|
||||
DelegationSet set = createSet(client);
|
||||
String zone = createZone(client, "a.example.com.", null).hostedZone().id();
|
||||
try {
|
||||
for (String name : List.of("A.EXAMPLE.COM", "child.a.example.com.", "example.com.")) {
|
||||
assertError("ConflictingDomainExists", () -> createZone(client, name, set.id()));
|
||||
}
|
||||
String sibling = createZone(client, "b.example.com.", set.id()).hostedZone().id();
|
||||
client.deleteHostedZone(r -> r.id(sibling));
|
||||
} finally {
|
||||
client.deleteHostedZone(r -> r.id(zone));
|
||||
client.deleteReusableDelegationSet(r -> r.id(set.id()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void privateZonesCannotUseOrPromoteAReusableSet() {
|
||||
try (Route53Client client = client("741686000014")) {
|
||||
DelegationSet set = createSet(client);
|
||||
String zone = client.createHostedZone(r -> r.name("private.example.")
|
||||
.callerReference(UUID.randomUUID().toString())
|
||||
.vpc(v -> v.vpcId("vpc-delegation-private").vpcRegion("us-east-1"))).hostedZone().id();
|
||||
try {
|
||||
assertError("InvalidArgument", () -> client.createReusableDelegationSet(r ->
|
||||
r.callerReference(UUID.randomUUID().toString()).hostedZoneId(zone)));
|
||||
assertError("InvalidInput", () -> client.createHostedZone(r -> r.name("other.private.example.")
|
||||
.callerReference(UUID.randomUUID().toString()).delegationSetId(set.id())
|
||||
.vpc(v -> v.vpcId("vpc-delegation-private").vpcRegion("us-east-1"))));
|
||||
assertEquals(1, client.getHostedZoneCount().hostedZoneCount());
|
||||
} finally {
|
||||
client.deleteHostedZone(r -> r.id(zone));
|
||||
client.deleteReusableDelegationSet(r -> r.id(set.id()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingAndForeignResourcesFailWithoutCreatingZonesOrSets() {
|
||||
try (Route53Client owner = client("741686000015"); Route53Client stranger = client("741686000016")) {
|
||||
DelegationSet set = createSet(owner);
|
||||
String zone = createZone(owner, "owned.example.", null).hostedZone().id();
|
||||
try {
|
||||
assertError("NoSuchDelegationSet", () -> createZone(stranger, "stranger.example.", set.id()));
|
||||
assertError("NoSuchDelegationSet", () -> createZone(owner, "missing.example.", "NMissing"));
|
||||
assertError("HostedZoneNotFound", () -> stranger.createReusableDelegationSet(r ->
|
||||
r.callerReference(UUID.randomUUID().toString()).hostedZoneId(zone)));
|
||||
assertError("HostedZoneNotFound", () -> owner.createReusableDelegationSet(r ->
|
||||
r.callerReference(UUID.randomUUID().toString()).hostedZoneId("ZMissing")));
|
||||
assertEquals(0, stranger.getHostedZoneCount().hostedZoneCount());
|
||||
assertTrue(stranger.listReusableDelegationSets().delegationSets().isEmpty());
|
||||
assertEquals(1, owner.getHostedZoneCount().hostedZoneCount());
|
||||
} finally {
|
||||
owner.deleteHostedZone(r -> r.id(zone));
|
||||
owner.deleteReusableDelegationSet(r -> r.id(set.id()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void hostedZoneFilteringByDelegationSetHappensBeforePagination() {
|
||||
try (Route53Client client = client("741686000040")) {
|
||||
DelegationSet selected = createSet(client);
|
||||
DelegationSet other = createSet(client);
|
||||
String alpha = createZone(client, "alpha.example.", selected.id()).hostedZone().id();
|
||||
String beta = createZone(client, "beta.example.", selected.id()).hostedZone().id();
|
||||
String excluded = createZone(client, "excluded.example.", other.id()).hostedZone().id();
|
||||
String ordinary = createZone(client, "aardvark.example.", null).hostedZone().id();
|
||||
try {
|
||||
ListHostedZonesResponse first = client.listHostedZones(r -> r.delegationSetId(selected.id()).maxItems("1"));
|
||||
assertEquals(List.of(alpha), first.hostedZones().stream().map(zone -> zone.id()).toList());
|
||||
assertTrue(first.isTruncated());
|
||||
ListHostedZonesResponse second = client.listHostedZones(r -> r.delegationSetId(selected.id())
|
||||
.marker(first.nextMarker()).maxItems("1"));
|
||||
assertEquals(List.of(beta), second.hostedZones().stream().map(zone -> zone.id()).toList());
|
||||
assertFalse(second.isTruncated());
|
||||
assertEquals(List.of(excluded), client.listHostedZones(r -> r.delegationSetId(other.id()))
|
||||
.hostedZones().stream().map(zone -> zone.id()).toList());
|
||||
assertEquals(4, client.listHostedZones().hostedZones().size());
|
||||
} finally {
|
||||
for (String id : List.of(alpha, beta, excluded, ordinary)) {
|
||||
client.deleteHostedZone(r -> r.id(id));
|
||||
}
|
||||
client.deleteReusableDelegationSet(r -> r.id(selected.id()));
|
||||
client.deleteReusableDelegationSet(r -> r.id(other.id()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void hostedZoneFilteringValidatesTheSetEvenWhenNoZonesExist() {
|
||||
try (Route53Client owner = client("741686000041"); Route53Client stranger = client("741686000042")) {
|
||||
DelegationSet empty = createSet(owner);
|
||||
try {
|
||||
assertTrue(owner.listHostedZones(r -> r.delegationSetId(empty.id())).hostedZones().isEmpty());
|
||||
assertError("NoSuchDelegationSet", () -> owner.listHostedZones(r -> r.delegationSetId("NMissing")));
|
||||
assertError("NoSuchDelegationSet", () -> stranger.listHostedZones(r -> r.delegationSetId(empty.id())));
|
||||
} finally {
|
||||
owner.deleteReusableDelegationSet(r -> r.id(empty.id()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Route53Client client(String account) {
|
||||
return AwsTestClients.create(Route53Client.builder(), account, Region.US_EAST_1);
|
||||
}
|
||||
|
||||
private DelegationSet createSet(Route53Client client) {
|
||||
return client.createReusableDelegationSet(r -> r.callerReference(UUID.randomUUID().toString())).delegationSet();
|
||||
}
|
||||
|
||||
private CreateHostedZoneResponse createZone(Route53Client client, String name, String delegationSetId) {
|
||||
return client.createHostedZone(r -> r.name(name).callerReference(UUID.randomUUID().toString())
|
||||
.delegationSetId(delegationSetId));
|
||||
}
|
||||
|
||||
private void assertError(String code, Runnable action) {
|
||||
Route53Exception error = assertThrows(Route53Exception.class, action::run);
|
||||
assertEquals(400, error.statusCode());
|
||||
assertEquals(code, error.awsErrorDetails().errorCode());
|
||||
}
|
||||
}
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
package io.github.hectorvent.floci.services.route53;
|
||||
|
||||
import io.github.hectorvent.floci.testing.AwsTestClients;
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
import org.junit.jupiter.api.extension.AfterAllCallback;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.route53.Route53Client;
|
||||
import software.amazon.awssdk.services.route53.model.Route53Exception;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class Route53DelegationSetsIamEnforcementIntegrationTest {
|
||||
private static final String ACCOUNT = "741686000030";
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI baseUri;
|
||||
|
||||
private final PartitionCleanup CLEANUP = new PartitionCleanup();
|
||||
@RegisterExtension
|
||||
final AfterAllCallback classCleanup = CLEANUP::afterEach;
|
||||
private String implicitDenyKey;
|
||||
private String explicitDenyKey;
|
||||
private String allowKey;
|
||||
private String scopedAllowKey;
|
||||
private String scopedDenyKey;
|
||||
private String selectedSet;
|
||||
private String otherSet;
|
||||
|
||||
@BeforeAll
|
||||
void createSharedFixtures() {
|
||||
implicitDenyKey = userWithPolicy(null);
|
||||
explicitDenyKey = userWithPolicy("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"*","Resource":"*"},
|
||||
{"Effect":"Deny","Action":"route53:*","Resource":"*"}]}
|
||||
""");
|
||||
allowKey = userWithPolicy("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"route53:*","Resource":"*"}]}
|
||||
""");
|
||||
Route53Client root = client(ACCOUNT);
|
||||
CLEANUP.register(root::close);
|
||||
selectedSet = createSet(root);
|
||||
CLEANUP.register(() -> root.deleteReusableDelegationSet(r -> r.id(selectedSet)));
|
||||
otherSet = createSet(root);
|
||||
CLEANUP.register(() -> root.deleteReusableDelegationSet(r -> r.id(otherSet)));
|
||||
scopedAllowKey = userWithPolicy("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Action":["route53:GetReusableDelegationSet","route53:DeleteReusableDelegationSet"],
|
||||
"Resource":"arn:aws:route53:::delegationset/%s"}]}
|
||||
""".formatted(selectedSet));
|
||||
scopedDenyKey = userWithPolicy("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"*","Resource":"*"},
|
||||
{"Effect":"Deny","Action":["route53:GetReusableDelegationSet","route53:DeleteReusableDelegationSet"],
|
||||
"Resource":"arn:aws:route53:::delegationset/%s"}]}
|
||||
""".formatted(selectedSet));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"Create,true", "Get,true", "List,true", "Delete,true",
|
||||
"Create,false", "Get,false", "List,false", "Delete,false"})
|
||||
void missingPermissionsAndExplicitDeniesApplyToEveryOperation(String operation, boolean explicitDeny) {
|
||||
try (Route53Client client = client(explicitDeny ? explicitDenyKey : implicitDenyKey)) {
|
||||
Runnable call = switch (operation) {
|
||||
case "Create" -> () -> client.createReusableDelegationSet(r -> r.callerReference(UUID.randomUUID().toString()));
|
||||
case "Get" -> () -> client.getReusableDelegationSet(r -> r.id("NMissing"));
|
||||
case "List" -> () -> client.listReusableDelegationSets();
|
||||
case "Delete" -> () -> client.deleteReusableDelegationSet(r -> r.id("NMissing"));
|
||||
default -> throw new IllegalArgumentException(operation);
|
||||
};
|
||||
assertDenied(call);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAllowedCallerCanCompleteTheDelegationSetLifecycle() {
|
||||
try (Route53Client client = client(allowKey)) {
|
||||
String id = createSet(client);
|
||||
try {
|
||||
assertEquals(id, client.getReusableDelegationSet(r -> r.id(id)).delegationSet().id());
|
||||
assertEquals(id, client.listReusableDelegationSets().delegationSets().stream()
|
||||
.filter(set -> set.id().equals(id)).findFirst().orElseThrow().id());
|
||||
} finally {
|
||||
client.deleteReusableDelegationSet(r -> r.id(id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void resourceScopedAllowsGrantOnlyTheSelectedSet() {
|
||||
try (Route53Client reader = client(scopedAllowKey)) {
|
||||
assertEquals(selectedSet, reader.getReusableDelegationSet(r -> r.id(selectedSet)).delegationSet().id());
|
||||
assertDenied(() -> reader.getReusableDelegationSet(r -> r.id(otherSet)));
|
||||
assertDenied(() -> reader.deleteReusableDelegationSet(r -> r.id(otherSet)));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"plain", "encodedPrefix", "matrix", "matrixEncodedId"})
|
||||
void aScopedDenyCannotBeBypassedByEncodedIdsOrOperationHeaders(String variant) {
|
||||
String selected = selectedSet;
|
||||
String other = otherSet;
|
||||
String key = scopedDenyKey;
|
||||
String path = "/2013-04-01/delegationset/"
|
||||
+ (variant.contains("Prefix") ? "%2Fdelegationset%2F" : "")
|
||||
+ (variant.equals("matrixEncodedId") ? "%4E" + selected.substring(1) : selected)
|
||||
+ (variant.startsWith("matrix") ? ";ignored=1" : "");
|
||||
given().urlEncodingEnabled(false).header("Authorization", auth(ACCOUNT, "route53"))
|
||||
.get(path).then().statusCode(200).body(containsString(selected));
|
||||
try (Route53Client reader = client(key)) {
|
||||
assertEquals(other, reader.getReusableDelegationSet(r -> r.id(other)).delegationSet().id());
|
||||
for (String method : new String[]{"GET", "DELETE"}) {
|
||||
given().urlEncodingEnabled(false).header("Authorization", auth(key, "route53"))
|
||||
.header("X-Amz-Target", "Route53.ListReusableDelegationSets")
|
||||
.queryParam("Action", "ListReusableDelegationSets")
|
||||
.request(method, path)
|
||||
.then().statusCode(403).body(containsString("<Code>AccessDenied</Code>"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"Create,literal", "Get,literal", "List,literal", "Delete,literal",
|
||||
"Create,separator", "Get,separator", "List,separator", "Delete,separator"})
|
||||
void percentEncodedRouteLiteralsStillEnforceTheSelectedOperation(String operation, String variant) {
|
||||
String key = explicitDenyKey;
|
||||
String method = switch (operation) {
|
||||
case "Create" -> "POST";
|
||||
case "Delete" -> "DELETE";
|
||||
default -> "GET";
|
||||
};
|
||||
String path = (variant.equals("literal") ? "/2013-04-01/%64elegationset"
|
||||
: "/2013-04-01%2Fdelegationset;ignored=1")
|
||||
+ (operation.equals("Get") || operation.equals("Delete") ? "/NMissing" : "");
|
||||
given().urlEncodingEnabled(false).header("Authorization", auth(key, "route53"))
|
||||
.contentType("application/xml").body("<CreateReusableDelegationSetRequest><CallerReference>"
|
||||
+ UUID.randomUUID() + "</CallerReference></CreateReusableDelegationSetRequest>")
|
||||
.request(method, path).then().statusCode(403).body(containsString("<Code>AccessDenied</Code>"));
|
||||
}
|
||||
|
||||
private String userWithPolicy(String policy) {
|
||||
String user = "r53-delegation-" + UUID.randomUUID();
|
||||
String key = EnforcementFixtures.createUser(CLEANUP, baseUri.getPort(), auth(ACCOUNT, "iam"), user).accessKeyId();
|
||||
if (policy != null) {
|
||||
EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ACCOUNT, "iam"), user, "delegation", policy);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
private Route53Client client(String key) {
|
||||
return AwsTestClients.create(Route53Client.builder(), key, Region.US_EAST_1, baseUri);
|
||||
}
|
||||
|
||||
private String createSet(Route53Client client) {
|
||||
return client.createReusableDelegationSet(r -> r.callerReference(UUID.randomUUID().toString())).delegationSet().id();
|
||||
}
|
||||
|
||||
private void assertDenied(Runnable call) {
|
||||
Route53Exception error = assertThrows(Route53Exception.class, call::run);
|
||||
assertEquals(403, error.statusCode());
|
||||
assertEquals("AccessDenied", error.awsErrorDetails().errorCode());
|
||||
}
|
||||
}
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
package io.github.hectorvent.floci.services.route53;
|
||||
|
||||
import io.github.hectorvent.floci.testing.AwsTestClients;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.route53.Route53Client;
|
||||
import software.amazon.awssdk.services.route53.model.CreateReusableDelegationSetResponse;
|
||||
import software.amazon.awssdk.services.route53.model.DelegationSet;
|
||||
import software.amazon.awssdk.services.route53.model.ListReusableDelegationSetsResponse;
|
||||
import software.amazon.awssdk.services.route53.model.Route53Exception;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class Route53DelegationSetsIntegrationTest {
|
||||
@Test
|
||||
void createGetAndDeleteRoundTripThroughAwsSdk() {
|
||||
try (Route53Client client = client("741686000001", Region.US_EAST_1)) {
|
||||
String reference = "delegation<&>" + UUID.randomUUID();
|
||||
CreateReusableDelegationSetResponse response = client.createReusableDelegationSet(r -> r.callerReference(reference));
|
||||
DelegationSet created = response.delegationSet();
|
||||
try {
|
||||
assertTrue(created.id().startsWith("N"));
|
||||
assertEquals(reference, created.callerReference());
|
||||
assertEquals(201, response.sdkHttpResponse().statusCode());
|
||||
assertEquals("/2013-04-01/delegationset/" + created.id(),
|
||||
URI.create(response.sdkHttpResponse().firstMatchingHeader("Location").orElseThrow()).getPath());
|
||||
given().header("Authorization", "AWS4-HMAC-SHA256 Credential=741686000001"
|
||||
+ "/20261030/us-east-1/route53/aws4_request, SignedHeaders=host, Signature=abc")
|
||||
.get("/2013-04-01/delegationset/" + created.id()).then().statusCode(200)
|
||||
.body(containsString("<Id>/delegationset/" + created.id() + "</Id>"))
|
||||
.body(containsString("<CallerReference>delegation<&>"));
|
||||
assertEquals(4, created.nameServers().size());
|
||||
assertEquals(1, client.getAccountLimit(r -> r.type("MAX_REUSABLE_DELEGATION_SETS_BY_OWNER")).count());
|
||||
assertEquals(created, client.getReusableDelegationSet(r -> r.id(created.id())).delegationSet());
|
||||
} finally {
|
||||
client.deleteReusableDelegationSet(r -> r.id(created.id()));
|
||||
}
|
||||
assertError("NoSuchDelegationSet", () -> client.getReusableDelegationSet(r -> r.id(created.id())));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateCallerReferenceIsRejectedWithoutCreatingAnotherSet() {
|
||||
try (Route53Client client = client("741686000002", Region.US_EAST_1)) {
|
||||
String reference = UUID.randomUUID().toString();
|
||||
String id = client.createReusableDelegationSet(r -> r.callerReference(reference)).delegationSet().id();
|
||||
try {
|
||||
assertError("DelegationSetAlreadyCreated", () ->
|
||||
client.createReusableDelegationSet(r -> r.callerReference(reference)));
|
||||
assertEquals(1, client.listReusableDelegationSets().delegationSets().size());
|
||||
} finally {
|
||||
client.deleteReusableDelegationSet(r -> r.id(id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void listIncludesEverySetOnceUsingFirstUnseenId() {
|
||||
try (Route53Client client = client("741686000003", Region.US_EAST_1)) {
|
||||
List<String> ids = new ArrayList<>();
|
||||
try {
|
||||
for (int i = 0; i < 3; i++) {
|
||||
ids.add(client.createReusableDelegationSet(r -> r.callerReference(UUID.randomUUID().toString()))
|
||||
.delegationSet().id());
|
||||
}
|
||||
List<ListReusableDelegationSetsResponse> pages = new ArrayList<>();
|
||||
String marker = null;
|
||||
do {
|
||||
String next = marker;
|
||||
ListReusableDelegationSetsResponse page = client.listReusableDelegationSets(r ->
|
||||
r.maxItems("1").marker(next));
|
||||
pages.add(page);
|
||||
marker = page.nextMarker();
|
||||
} while (pages.getLast().isTruncated() && pages.size() < 4);
|
||||
assertEquals(3, pages.size());
|
||||
assertEquals(ids.stream().sorted().toList(), pages.stream()
|
||||
.flatMap(p -> p.delegationSets().stream()).map(DelegationSet::id).toList());
|
||||
assertTrue(pages.getFirst().isTruncated());
|
||||
assertEquals(pages.get(1).delegationSets().getFirst().id().replace("/delegationset/", ""),
|
||||
pages.getFirst().nextMarker());
|
||||
assertFalse(pages.getLast().isTruncated());
|
||||
assertEquals(null, pages.getLast().nextMarker());
|
||||
} finally {
|
||||
ids.forEach(id -> client.deleteReusableDelegationSet(r -> r.id(id)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void setsAreAccountScopedAndGlobalAcrossRegions() {
|
||||
try (Route53Client owner = client("741686000004", Region.US_EAST_1);
|
||||
Route53Client otherRegion = client("741686000004", Region.EU_WEST_1);
|
||||
Route53Client stranger = client("741686000005", Region.US_EAST_1)) {
|
||||
String reference = UUID.randomUUID().toString();
|
||||
DelegationSet set = owner.createReusableDelegationSet(r -> r.callerReference(reference)).delegationSet();
|
||||
try {
|
||||
assertEquals(set, otherRegion.getReusableDelegationSet(r -> r.id(set.id())).delegationSet());
|
||||
assertTrue(stranger.listReusableDelegationSets().delegationSets().isEmpty());
|
||||
assertError("NoSuchDelegationSet", () -> stranger.getReusableDelegationSet(r -> r.id(set.id())));
|
||||
assertError("NoSuchDelegationSet", () -> stranger.deleteReusableDelegationSet(r -> r.id(set.id())));
|
||||
String foreignId = stranger.createReusableDelegationSet(r -> r.callerReference(reference))
|
||||
.delegationSet().id();
|
||||
stranger.deleteReusableDelegationSet(r -> r.id(foreignId));
|
||||
} finally {
|
||||
owner.deleteReusableDelegationSet(r -> r.id(set.id()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {0, 129})
|
||||
void callerReferenceLengthIsValidated(int length) {
|
||||
try (Route53Client client = client("741686000006", Region.US_EAST_1)) {
|
||||
assertError("InvalidInput", () -> client.createReusableDelegationSet(r -> r.callerReference("x".repeat(length))));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"0", "-1", "no"})
|
||||
void invalidPageSizeHasAnAwsXmlError(String size) {
|
||||
given().queryParam("maxitems", size).when().get("/2013-04-01/delegationset")
|
||||
.then().statusCode(400).body(containsString("<Code>InvalidInput</Code>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void positivePageSizeBeyondIntegerRangeIsAccepted() {
|
||||
try (Route53Client client = client("741686000007", Region.US_EAST_1)) {
|
||||
ListReusableDelegationSetsResponse page = client.listReusableDelegationSets(r -> r.maxItems("2147483648"));
|
||||
assertEquals("2147483648", page.maxItems());
|
||||
assertFalse(page.isTruncated());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"<Wrong><CallerReference>wrong</CallerReference></Wrong>",
|
||||
"<CreateReusableDelegationSetRequest/>",
|
||||
"<CreateReusableDelegationSetRequest><CallerReference>x</CallerReference></CreateReusableDelegationSetRequest>broken"
|
||||
})
|
||||
void malformedCreateRequestsReturnXmlErrors(String body) {
|
||||
given().contentType("application/xml").body(body).post("/2013-04-01/delegationset")
|
||||
.then().statusCode(400).body(containsString("<Code>InvalidInput</Code>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void callerReferenceMaximumLengthIsAccepted() {
|
||||
try (Route53Client client = client("741686000008", Region.US_EAST_1)) {
|
||||
String id = client.createReusableDelegationSet(r -> r.callerReference("x".repeat(128))).delegationSet().id();
|
||||
client.deleteReusableDelegationSet(r -> r.id(id));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void overlongIdsAndMarkersReturnXmlErrors() {
|
||||
try (Route53Client client = client("741686000009", Region.US_EAST_1)) {
|
||||
assertError("InvalidInput", () -> client.getReusableDelegationSet(r -> r.id("N".repeat(33))));
|
||||
assertError("InvalidInput", () -> client.deleteReusableDelegationSet(r -> r.id("N".repeat(33))));
|
||||
assertError("InvalidInput", () -> client.listReusableDelegationSets(r -> r.marker("N".repeat(65))));
|
||||
}
|
||||
}
|
||||
|
||||
private Route53Client client(String account, Region region) {
|
||||
return AwsTestClients.create(Route53Client.builder(), account, region);
|
||||
}
|
||||
|
||||
private void assertError(String code, Runnable action) {
|
||||
Route53Exception error = assertThrows(Route53Exception.class, action::run);
|
||||
assertEquals(400, error.statusCode());
|
||||
assertEquals(code, error.awsErrorDetails().errorCode());
|
||||
}
|
||||
}
|
||||
+301
@@ -0,0 +1,301 @@
|
||||
package io.github.hectorvent.floci.services.route53;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestContext;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.route53.model.DelegationSet;
|
||||
import io.github.hectorvent.floci.services.route53.model.HostedZone;
|
||||
import io.github.hectorvent.floci.services.route53.model.ResourceRecord;
|
||||
import io.github.hectorvent.floci.services.route53.model.ResourceRecordSet;
|
||||
import io.github.hectorvent.floci.testing.StorageFactories;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Callable;
|
||||
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.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class Route53DelegationSetsServiceTest {
|
||||
private static final String ACCOUNT = "741686000020";
|
||||
|
||||
@TempDir
|
||||
Path directory;
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"persistent", "hybrid", "wal"})
|
||||
void setsAndZoneLinksSurviveStorageReloadAndConfigurationChanges(String mode) {
|
||||
DelegationSet set;
|
||||
String zoneId;
|
||||
try (Fixture fixture = fixture(mode, "original")) {
|
||||
HostedZone zone = fixture.service().createHostedZone("saved.example.", "source", null, null).zone();
|
||||
zoneId = zone.getId();
|
||||
set = fixture.service().createReusableDelegationSet("saved", "/hostedzone/" + zoneId);
|
||||
}
|
||||
try (Fixture reloaded = fixture(mode, "changed")) {
|
||||
Route53Service service = reloaded.service();
|
||||
assertEquals(set, service.getReusableDelegationSet("/delegationset/" + set.id()));
|
||||
assertEquals(set, service.getDelegationSet(service.getHostedZone(zoneId)));
|
||||
assertError("DelegationSetInUse", () -> service.deleteReusableDelegationSet(set.id()));
|
||||
assertError("DelegationSetAlreadyCreated", () -> service.createReusableDelegationSet("saved", null));
|
||||
HostedZone next = service.createHostedZone("next.example.", "next", null, null, set.id()).zone();
|
||||
assertEquals(set, service.getDelegationSet(next));
|
||||
assertTrue(service.listResourceRecordSets(next.getId(), null, null, 100).stream()
|
||||
.filter(record -> "SOA".equals(record.getType())).findFirst().orElseThrow()
|
||||
.getRecords().getFirst().getValue().startsWith(set.nameServers().getFirst() + ". "));
|
||||
service.deleteHostedZone(next.getId());
|
||||
service.deleteHostedZone(zoneId);
|
||||
service.deleteReusableDelegationSet(set.id());
|
||||
}
|
||||
try (Fixture reloaded = fixture(mode, "changed")) {
|
||||
assertEquals(0, reloaded.service().getReusableDelegationSetCount());
|
||||
assertEquals(0, reloaded.service().getHostedZoneCount());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aForeignReadCannotClaimAnOwnerlessLegacyZoneBeforePromotion() {
|
||||
RequestContext context = new RequestContext();
|
||||
context.setAccountId("741686000099");
|
||||
@SuppressWarnings("unchecked")
|
||||
Instance<RequestContext> instance = mock(Instance.class);
|
||||
when(instance.get()).thenReturn(context);
|
||||
InMemoryStorage<String, HostedZone> legacy = new InMemoryStorage<>();
|
||||
legacy.put("ZLEGACY", new HostedZone("ZLEGACY", "legacy.example.", "legacy", null, false));
|
||||
AccountAwareStorageBackend<HostedZone> zones = new AccountAwareStorageBackend<>(legacy, instance, ACCOUNT);
|
||||
StorageFactory factory = mock(StorageFactory.class);
|
||||
when(factory.create(anyString(), anyString(), any())).thenAnswer(invocation ->
|
||||
"route53-zones.json".equals(invocation.getArgument(1)) ? zones : AccountAwareStorageBackend.inMemory(ACCOUNT));
|
||||
RegionResolver resolver = mock(RegionResolver.class);
|
||||
when(resolver.getAccountId()).thenAnswer(ignored -> context.getAccountId());
|
||||
Route53Service service = new Route53Service(factory, config("original"), resolver, mock(Ec2Service.class));
|
||||
AwsException read = assertThrows(AwsException.class, () -> service.getHostedZone("ZLEGACY"));
|
||||
assertEquals("NoSuchHostedZone", read.getErrorCode());
|
||||
assertEquals(404, read.getHttpStatus());
|
||||
assertError("HostedZoneNotFound", () -> service.createReusableDelegationSet("foreign", "ZLEGACY"));
|
||||
context.setAccountId(ACCOUNT);
|
||||
service.createReusableDelegationSet("owner", "ZLEGACY");
|
||||
assertEquals(1, service.getReusableDelegationSetCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aForeignCallerCannotPromoteAnUnscopedLegacyZone() throws Exception {
|
||||
seedLegacyZone();
|
||||
try (Fixture fixture = fixture("persistent", "original", "741686000099")) {
|
||||
assertError("HostedZoneNotFound", () -> fixture.service().createReusableDelegationSet("foreign", "ZLEGACY"));
|
||||
assertEquals(0, fixture.service().getReusableDelegationSetCount());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyPublicZonesParticipateInConflictsBeforeTheirFirstRead() throws Exception {
|
||||
seedLegacyZone();
|
||||
try (Fixture fixture = fixture("persistent", "original")) {
|
||||
DelegationSet set = fixture.service().createReusableDelegationSet("set", null);
|
||||
assertError("ConflictingDomainExists", () -> fixture.service()
|
||||
.createHostedZone("child.legacy.example.", "child", null, null, set.id()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void promotionAfterConfigurationChangePreservesTheOriginalZoneAssignment() {
|
||||
String zoneId;
|
||||
try (Fixture fixture = fixture("persistent", "original")) {
|
||||
zoneId = fixture.service().createHostedZone("original.example.", "original", null, null).zone().getId();
|
||||
ResourceRecordSet ns = fixture.service().listResourceRecordSets(zoneId, null, null, 100).stream()
|
||||
.filter(record -> "NS".equals(record.getType())).findFirst().orElseThrow();
|
||||
ns.setRecords(List.of(new ResourceRecord("custom.nameserver.test.")));
|
||||
fixture.service().changeResourceRecordSets(zoneId, List.of(Map.of("action", "UPSERT", "rrs", ns)), null);
|
||||
}
|
||||
try (Fixture fixture = fixture("persistent", "changed")) {
|
||||
DelegationSet set = fixture.service().createReusableDelegationSet("promoted", zoneId);
|
||||
assertEquals(List.of("original-1.test", "original-2.test", "original-3.test", "original-4.test"),
|
||||
set.nameServers());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void promotionRecoversAnOlderZonesNameserversFromItsPersistedApexRecords() throws Exception {
|
||||
seedLegacyZone();
|
||||
try (Fixture fixture = fixture("persistent", "changed")) {
|
||||
DelegationSet set = fixture.service().createReusableDelegationSet("promoted", "ZLEGACY");
|
||||
assertEquals(List.of("original-1.test", "original-2.test", "original-3.test", "original-4.test"),
|
||||
set.nameServers());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void setQuotaAndMaximumPageSizeAreEnforcedAndDeletionFreesCapacity() {
|
||||
try (Fixture fixture = fixture("memory", "quota")) {
|
||||
Route53Service service = fixture.service();
|
||||
List<String> ids = new ArrayList<>();
|
||||
for (int i = 0; i < 100; i++) {
|
||||
ids.add(service.createReusableDelegationSet("ref-" + i, null).id());
|
||||
}
|
||||
assertError("LimitsExceeded", () -> service.createReusableDelegationSet("overflow", null));
|
||||
assertEquals(100, service.getReusableDelegationSetCount());
|
||||
assertEquals(100, service.pageReusableDelegationSets(null, "2147483648").items().size());
|
||||
String first = ids.stream().sorted().findFirst().orElseThrow();
|
||||
service.deleteReusableDelegationSet(first);
|
||||
assertEquals(99, service.pageReusableDelegationSets(first, "100").items().size());
|
||||
service.createReusableDelegationSet("replacement", null);
|
||||
assertEquals(100, service.getReusableDelegationSetCount());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void hostedZoneQuotaCountsOnlyZonesAssociatedWithThatSet() {
|
||||
try (Fixture fixture = fixture("memory", "quota")) {
|
||||
Route53Service service = fixture.service();
|
||||
DelegationSet set = service.createReusableDelegationSet("set", null);
|
||||
String first = null;
|
||||
for (int i = 0; i < 100; i++) {
|
||||
HostedZone zone = service.createHostedZone("zone-" + i + ".example.", "zone-" + i,
|
||||
null, null, set.id()).zone();
|
||||
if (first == null) {
|
||||
first = zone.getId();
|
||||
}
|
||||
}
|
||||
assertError("TooManyHostedZones", () ->
|
||||
service.createHostedZone("overflow.example.", "overflow", null, null, set.id()));
|
||||
DelegationSet other = service.createReusableDelegationSet("other", null);
|
||||
service.createHostedZone("other.example.", "other", null, null, other.id());
|
||||
service.deleteHostedZone(first);
|
||||
service.createHostedZone("replacement.example.", "replacement", null, null, set.id());
|
||||
assertEquals(101, service.getHostedZoneCount());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentDuplicateReferencesCreateExactlyOneSet() throws Exception {
|
||||
try (Fixture fixture = fixture("memory", "concurrent");
|
||||
ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
Route53Service service = fixture.service();
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
List<Callable<String>> calls = new ArrayList<>();
|
||||
for (int i = 0; i < 16; i++) {
|
||||
calls.add(() -> {
|
||||
start.await();
|
||||
return outcome(() -> service.createReusableDelegationSet("shared", null));
|
||||
});
|
||||
}
|
||||
List<Future<String>> futures = calls.stream().map(executor::submit).toList();
|
||||
start.countDown();
|
||||
List<String> results = new ArrayList<>();
|
||||
for (Future<String> future : futures) {
|
||||
results.add(future.get(10, TimeUnit.SECONDS));
|
||||
}
|
||||
assertEquals(1, results.stream().filter("success"::equals).count());
|
||||
assertEquals(15, results.stream().filter("DelegationSetAlreadyCreated"::equals).count());
|
||||
assertEquals(1, service.getReusableDelegationSetCount());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void racingDeleteAndZoneCreationCannotLeaveADanglingSetReference() throws Exception {
|
||||
try (Fixture fixture = fixture("memory", "concurrent");
|
||||
ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
Route53Service service = fixture.service();
|
||||
DelegationSet set = service.createReusableDelegationSet("racing", null);
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
Future<String> create = executor.submit(() -> {
|
||||
start.await();
|
||||
return outcome(() -> service.createHostedZone("racing.example.", "racing", null, null, set.id()));
|
||||
});
|
||||
Future<String> delete = executor.submit(() -> {
|
||||
start.await();
|
||||
return outcome(() -> service.deleteReusableDelegationSet(set.id()));
|
||||
});
|
||||
start.countDown();
|
||||
String createResult = create.get(10, TimeUnit.SECONDS);
|
||||
String deleteResult = delete.get(10, TimeUnit.SECONDS);
|
||||
if ("success".equals(createResult)) {
|
||||
assertEquals("DelegationSetInUse", deleteResult);
|
||||
assertEquals(set, service.getReusableDelegationSet(set.id()));
|
||||
assertEquals(1, service.getHostedZoneCount());
|
||||
} else {
|
||||
assertEquals("NoSuchDelegationSet", createResult);
|
||||
assertEquals("success", deleteResult);
|
||||
assertEquals(0, service.getHostedZoneCount());
|
||||
assertEquals(0, service.getReusableDelegationSetCount());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String outcome(Runnable action) {
|
||||
try {
|
||||
action.run();
|
||||
return "success";
|
||||
} catch (AwsException e) {
|
||||
return e.getErrorCode();
|
||||
}
|
||||
}
|
||||
|
||||
private void assertError(String code, Runnable action) {
|
||||
AwsException error = assertThrows(AwsException.class, action::run);
|
||||
assertEquals(code, error.getErrorCode());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
|
||||
private void seedLegacyZone() throws Exception {
|
||||
Files.writeString(directory.resolve("route53-zones.json"), """
|
||||
{"ZLEGACY":{"id":"ZLEGACY","name":"legacy.example.","callerReference":"legacy",
|
||||
"ownerAccountId":"741686000020","privateZone":false}}
|
||||
""");
|
||||
Files.writeString(directory.resolve("route53-records.json"), """
|
||||
{"ZLEGACY":[{"name":"legacy.example.","type":"NS","ttl":172800,"records":[
|
||||
{"value":"original-1.test."},{"value":"original-2.test."},
|
||||
{"value":"original-3.test."},{"value":"original-4.test."}]}]}
|
||||
""");
|
||||
}
|
||||
|
||||
private Fixture fixture(String mode, String prefix) {
|
||||
return fixture(mode, prefix, ACCOUNT);
|
||||
}
|
||||
|
||||
private Fixture fixture(String mode, String prefix, String callerAccount) {
|
||||
EmulatorConfig config = config(prefix);
|
||||
StorageFactory factory = StorageFactories.open(config, mode);
|
||||
return new Fixture(factory, new Route53Service(factory, config, new RegionResolver("us-east-1", callerAccount),
|
||||
mock(Ec2Service.class)));
|
||||
}
|
||||
|
||||
private EmulatorConfig config(String prefix) {
|
||||
EmulatorConfig config = StorageFactories.config(directory, ACCOUNT);
|
||||
when(config.services().route53().defaultNameserver1()).thenReturn(prefix + "-1.test.");
|
||||
when(config.services().route53().defaultNameserver2()).thenReturn(prefix + "-2.test.");
|
||||
when(config.services().route53().defaultNameserver3()).thenReturn(prefix + "-3.test.");
|
||||
when(config.services().route53().defaultNameserver4()).thenReturn(prefix + "-4.test.");
|
||||
return config;
|
||||
}
|
||||
|
||||
private record Fixture(StorageFactory factory, Route53Service service) implements AutoCloseable {
|
||||
@Override
|
||||
public void close() {
|
||||
factory.shutdownAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,18 @@ public final class AwsTestClients {
|
||||
/** Selects a transport explicitly for operations requiring methods such as PATCH. */
|
||||
public static <B extends AwsClientBuilder<B, C> & AwsSyncClientBuilder<B, C>, C> C create(
|
||||
B builder, String account, Region region, SdkHttpClient.Builder<?> httpClientBuilder) {
|
||||
return builder.endpointOverride(URI.create("http://localhost:" + RestAssured.port))
|
||||
return create(builder, account, region, httpClientBuilder, URI.create("http://localhost:" + RestAssured.port));
|
||||
}
|
||||
|
||||
/** Explicit endpoint for class fixtures created before RestAssured's per-test port is installed. */
|
||||
public static <B extends AwsClientBuilder<B, C> & AwsSyncClientBuilder<B, C>, C> C create(
|
||||
B builder, String account, Region region, URI endpoint) {
|
||||
return create(builder, account, region, UrlConnectionHttpClient.builder(), endpoint);
|
||||
}
|
||||
|
||||
private static <B extends AwsClientBuilder<B, C> & AwsSyncClientBuilder<B, C>, C> C create(
|
||||
B builder, String account, Region region, SdkHttpClient.Builder<?> httpClientBuilder, URI endpoint) {
|
||||
return builder.endpointOverride(endpoint)
|
||||
.httpClientBuilder(httpClientBuilder).region(region)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(account, "test")))
|
||||
.build();
|
||||
|
||||
Reference in new issue
Block a user