fix(route53): populate record change IAM conditions (#8297)

* fix(route53): populate record change IAM conditions
* fix(route53): align DNS identity and preserve XML validation errors
* fix(route53): read record change conditions from the generated table
This commit is contained in:
luiseterc authored and GitHub committed 2026-11-14 12:13:47 -04:00
1 parent d5b7a11f89
commit e2712cf344
19 files changed
+846 -156

No files matched your search

@@ -127,7 +127,7 @@ class IamConditionContextResolverTest {
resolver = new IamConditionContextResolver(
dynamoDbFacadeInstance, ec2ServiceInstance, s3ServiceInstance, logsServiceInstance,
crossAccountServiceInstance, iamServiceInstance,
lambdaWebServiceInstance,
lambdaWebServiceInstance, spellings(new ShapeNamingSpelling()),
requestContext, config,
null, serviceCatalog);
}
@@ -169,6 +169,42 @@ class IamConditionContextResolverTest {
webRequest("/2025-03-07/web-functions/app/list-endpoints", "{}")));
}
/**
* A change batch carries the keys the generated table names for its action, read from the elements its members
* name and spelled by the namespace's service for each member's shape; an element of the same name elsewhere is
* not read.
*/
@Test
void aChangeBatchCarriesTheKeysItsMembersNameSpelledByShape() {
String body = """
<ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<ChangeBatch><Changes>
<Change><Action>UPSERT</Action><ResourceRecordSet><Name>Probe.Example.test</Name><Type>A</Type>
<GeoLocation><Name>elsewhere.example.test</Name></GeoLocation></ResourceRecordSet></Change>
<Change><Action>DELETE</Action><ResourceRecordSet><Name>second.example.test.</Name>
<Type>TXT</Type></ResourceRecordSet></Change>
</Changes></ChangeBatch>
</ChangeResourceRecordSetsRequest>""";
assertEquals(Map.of(
"route53:ChangeResourceRecordSetsActions", List.of("ChangeAction:UPSERT", "ChangeAction:DELETE"),
"route53:ChangeResourceRecordSetsRecordTypes", List.of("RRType:A", "RRType:TXT"),
"route53:ChangeResourceRecordSetsNormalizedRecordNames",
List.of("DNSName:Probe.Example.test", "DNSName:second.example.test.")),
resolver.resolve("route53", "route53:ChangeResourceRecordSets", xmlRequest(body)));
assertNull(resolver.resolve("route53", "route53:ChangeResourceRecordSets",
xmlRequest("<ChangeResourceRecordSetsRequest><ChangeBatch><Changes>")), "a body that does not parse");
assertNull(resolver.resolve("route53", "route53:ListResourceRecordSets", xmlRequest(body)));
}
@Test
void aQueryRequestCarriesTheKeysItsMembersNameAsGiven() {
assertEquals(Map.of("redshift:DbUser", List.of("analyst")), resolver.resolve("redshift",
"redshift:GetClusterCredentials", formRequest("Action=GetClusterCredentials&DbUser=analyst")));
assertNull(resolver.resolve("redshift", "redshift:GetClusterCredentials",
formRequest("Action=GetClusterCredentials")));
}
@Test
void logStreamTagsUseRawParentNameAndRequestRegion() throws Exception {
ContainerRequestContext request = mock(ContainerRequestContext.class);
@@ -218,6 +254,35 @@ class IamConditionContextResolverTest {
return containerRequest;
}
/** An XML request whose body can be read again, as a real request's restored stream can. */
private static ContainerRequestContext xmlRequest(String body) {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
when(containerRequest.getEntityStream())
.thenAnswer(invocation -> new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)));
return containerRequest;
}
@SuppressWarnings("unchecked")
private static Instance<RequestConditionSpelling> spellings(RequestConditionSpelling... spellings) {
Instance<RequestConditionSpelling> instance = mock(Instance.class);
when(instance.isUnsatisfied()).thenReturn(spellings.length == 0);
when(instance.iterator()).thenAnswer(invocation -> List.of(spellings).iterator());
return instance;
}
/** Spells each Route 53 member as its shape and value, so a test sees which shape each value was read with. */
private static final class ShapeNamingSpelling implements RequestConditionSpelling {
@Override
public String namespace() {
return "route53";
}
@Override
public String spell(String shape, String value) {
return shape + ":" + value;
}
}
private ContainerRequestContext webRequest(String path, String body) throws Exception {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
UriInfo uriInfo = mock(UriInfo.class);
@@ -721,7 +786,7 @@ class IamConditionContextResolverTest {
private IamConditionContextResolver resolverAt(Instant now) {
return new IamConditionContextResolver(mock(Instance.class), mock(Instance.class), mock(Instance.class),
mock(Instance.class), mock(Instance.class), mock(Instance.class), mock(Instance.class),
requestContext, config, null,
spellings(), requestContext, config, null,
serviceCatalog, Clock.fixed(now, ZoneOffset.UTC));
}
@@ -0,0 +1,135 @@
package io.floci.aws.core.common;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.route53.Route53Client;
import software.amazon.awssdk.services.route53.model.Change;
import software.amazon.awssdk.services.route53.model.ResourceRecordSet;
import software.amazon.awssdk.services.route53.model.Route53Exception;
import java.net.URI;
import java.util.List;
import java.util.UUID;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class Route53RecordConditionsIntegrationTest {
@TestHTTPResource("/")
URI endpoint;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void authorizesEveryChangeAndPreservesTheBodyForTheController() {
String user = "dns-conditions-" + UUID.randomUUID();
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
auth("000000000000", "iam"), user);
try (Route53Client client = AwsTestClients.create(Route53Client.builder(), credentials.accessKeyId(),
credentials.secretAccessKey(), Region.US_EAST_1, endpoint);
Route53Client admin = AwsTestClients.create(Route53Client.builder(), "000000000000", Region.US_EAST_1, endpoint)) {
String zone = admin.createHostedZone(r -> r.name("example.test").callerReference(UUID.randomUUID().toString()))
.hostedZone().id();
String resource = "arn:aws:route53:::hostedzone/" + zone.replace("/hostedzone/", "");
String grant = """
{"Effect":"Allow","Action":"route53:ChangeResourceRecordSets","Resource":"%s",
"Condition":{"ForAllValues:StringEquals":{
"route53:ChangeResourceRecordSetsActions":["UPSERT"],
"route53:ChangeResourceRecordSetsRecordTypes":["A"],
"route53:ChangeResourceRecordSetsNormalizedRecordNames":["probe.example.test","second.example.test"]},
"Null":{"route53:ChangeResourceRecordSetsActions":"false",
"route53:ChangeResourceRecordSetsRecordTypes":"false",
"route53:ChangeResourceRecordSetsNormalizedRecordNames":"false"}}}
""".formatted(resource);
try {
policy(user, grant);
Change allowed = change("UPSERT", "PROBE.Example.test.", "A");
Change second = change("UPSERT", "second.example.test", "A");
denied(client, zone, allowed, change("UPSERT", "forbidden.example.test", "A"));
assertTrue(admin.listResourceRecordSets(r -> r.hostedZoneId(zone)).resourceRecordSets().stream()
.noneMatch(r -> r.name().equalsIgnoreCase("probe.example.test.")));
denied(client, zone, allowed, change("CREATE", "second.example.test", "A"));
denied(client, zone, allowed, change("UPSERT", "second.example.test", "TXT"));
client.changeResourceRecordSets(r -> r.hostedZoneId(zone).changeBatch(b -> b.changes(allowed, second)));
assertTrue(admin.listResourceRecordSets(r -> r.hostedZoneId(zone)).resourceRecordSets().stream()
.anyMatch(r -> r.name().equalsIgnoreCase("probe.example.test.") && r.resourceRecords().getFirst().value()
.equals("192.0.2.1")));
// Octal letters address the same record, rather than a second independently stored spelling.
client.changeResourceRecordSets(r -> r.hostedZoneId(zone).changeBatch(b -> b.changes(
change("UPSERT", "\\160robe.example.test", "A"))));
assertEquals(1, admin.listResourceRecordSets(r -> r.hostedZoneId(zone)).resourceRecordSets().stream()
.filter(r -> !List.of("NS", "SOA").contains(r.typeAsString())
&& !r.name().equals("second.example.test.")).count());
policy(user, "{\"Effect\":\"Allow\",\"Action\":\"route53:ChangeResourceRecordSets\",\"Resource\":\""
+ resource + "\"}");
Route53Exception invalid = assertThrows(Route53Exception.class,
() -> client.changeResourceRecordSets(r -> r.hostedZoneId(zone).changeBatch(b -> b.changes(
change("REPLACE", "probe.example.test", "A")))));
assertEquals(400, invalid.statusCode());
assertEquals("InvalidInput", invalid.awsErrorDetails().errorCode());
assertTrue(invalid.awsErrorDetails().sdkHttpResponse().firstMatchingHeader("Content-Type")
.orElse("").contains("xml"));
List<ResourceRecordSet> beforeInvalid = admin.listResourceRecordSets(r -> r.hostedZoneId(zone))
.resourceRecordSets();
given().port(endpoint.getPort()).header("Authorization", auth(credentials.accessKeyId(), "route53"))
.contentType("application/xml").body("<ChangeResourceRecordSetsRequest><ChangeBatch><Changes>")
.post("/2013-04-01/hostedzone/" + zone.replace("/hostedzone/", "") + "/rrset")
.then().statusCode(400).contentType("application/xml")
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"));
assertEquals(beforeInvalid, admin.listResourceRecordSets(r -> r.hostedZoneId(zone)).resourceRecordSets());
client.changeResourceRecordSets(r -> r.hostedZoneId(zone).changeBatch(b -> b.changes(
change("DELETE", "probe.example.test", "A"))));
assertTrue(admin.listResourceRecordSets(r -> r.hostedZoneId(zone)).resourceRecordSets().stream()
.filter(r -> !List.of("NS", "SOA").contains(r.typeAsString()))
.allMatch(r -> r.name().equals("second.example.test.")));
policy(user, grant + "," + """
{"Effect":"Deny","Action":"route53:ChangeResourceRecordSets","Resource":"%s",
"Condition":{"ForAnyValue:StringEquals":{
"route53:ChangeResourceRecordSetsNormalizedRecordNames":"second.example.test"}}}
""".formatted(resource));
denied(client, zone, allowed, second);
} finally {
List<ResourceRecordSet> records = admin.listResourceRecordSets(r -> r.hostedZoneId(zone))
.resourceRecordSets().stream().filter(r -> !List.of("NS", "SOA").contains(r.typeAsString())).toList();
if (!records.isEmpty()) {
admin.changeResourceRecordSets(r -> r.hostedZoneId(zone).changeBatch(b -> b.changes(records.stream()
.map(record -> Change.builder().action("DELETE").resourceRecordSet(record).build()).toList())));
}
admin.deleteHostedZone(r -> r.id(zone));
}
}
}
private Change change(String action, String name, String type) {
return Change.builder().action(action).resourceRecordSet(r -> r.name(name).type(type).ttl(60L)
.resourceRecords(v -> v.value(type.equals("TXT") ? "\"probe\"" : "192.0.2.1"))).build();
}
private void denied(Route53Client client, String zone, Change... changes) {
Route53Exception error = assertThrows(Route53Exception.class, () -> client.changeResourceRecordSets(
r -> r.hostedZoneId(zone).changeBatch(b -> b.changes(changes))));
assertEquals(403, error.statusCode());
}
private void policy(String user, String statements) {
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth("000000000000", "iam"), user,
"dns", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
}
}
@@ -153,7 +153,7 @@ class DynamoDbFacadeTest {
requestContext.setRegion(OTHER_REGION);
IamConditionContextResolver resolver = new IamConditionContextResolver(dynamoDb,
mock(Instance.class), mock(Instance.class), mock(Instance.class), mock(Instance.class),
mock(Instance.class), mock(Instance.class),
mock(Instance.class), mock(Instance.class), mock(Instance.class),
requestContext,
mock(EmulatorConfig.class),
null, mock(io.floci.aws.core.common.ResolvedServiceCatalog.class));
@@ -18,6 +18,8 @@ import static org.hamcrest.Matchers.not;
class Route53ChangeResourceRecordSetsIntegrationTest {
private static final String XML = "application/xml";
private static final String A_RECORDS =
"<TTL>300</TTL><ResourceRecords><ResourceRecord><Value>192.0.2.1</Value></ResourceRecord></ResourceRecords>";
@Test
void malformedChangeBatchIsRejectedAsInvalidInput() {
@@ -399,4 +401,60 @@ class Route53ChangeResourceRecordSetsIntegrationTest {
Arguments.of("EmptyChanges", emptyChanges),
Arguments.of("NoChangeBatch", noChangeBatch));
}
/** IAM reads a record's name from the record set's own {@code Name}, so the change must act on that one too. */
@Test
void aNameOutsideItsRecordSetIsNotTheRecordsName() {
String zoneId = createZone("nested-name.example.com.", "ref-nested-name");
given().contentType(XML)
.body(changeBatch("<Action>CREATE</Action>", "<Name>kept.nested-name.example.com.</Name><Type>A</Type>"
+ "<GeoLocation><Name>other.nested-name.example.com.</Name></GeoLocation>" + A_RECORDS))
.when().post("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then()
.statusCode(200);
given().get("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then().statusCode(200)
.body(containsString("kept.nested-name.example.com."))
.body(not(containsString("other.nested-name.example.com.")));
}
/** A second copy of an element its change or record set holds once would be a value IAM reads but no change uses. */
@ParameterizedTest
@MethodSource("repeatedElementCases")
void anElementHeldOnceIsRefusedWhenRepeated(String element, String change, String recordSet) {
String zoneId = createZone("repeated-" + element.toLowerCase() + ".example.com.", "ref-repeated-" + element);
given().contentType(XML)
.body(changeBatch(change, recordSet))
.when().post("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"))
.body("ErrorResponse.Error.Message", containsString(":" + element + "}"));
given().get("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then().statusCode(200)
.body(not(containsString("allowed.repeated.example.com.")))
.body(not(containsString("other.repeated.example.com.")));
}
private static Stream<Arguments> repeatedElementCases() {
String recordSet = "<Name>allowed.repeated.example.com.</Name><Type>A</Type>" + A_RECORDS;
return Stream.of(
Arguments.of("Name", "<Action>CREATE</Action>", recordSet
+ "<Name>other.repeated.example.com.</Name>"),
Arguments.of("Action", "<Action>CREATE</Action><Action>DELETE</Action>", recordSet),
Arguments.of("ResourceRecordSet", "<Action>CREATE</Action><ResourceRecordSet>"
+ "<Name>other.repeated.example.com.</Name><Type>A</Type>" + A_RECORDS
+ "</ResourceRecordSet>", recordSet));
}
/** One change, {@code change} holding its elements before the record set, which holds {@code recordSet}. */
private static String changeBatch(String change, String recordSet) {
return "<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2013-04-01/\">"
+ "<ChangeBatch><Changes><Change>" + change + "<ResourceRecordSet>" + recordSet
+ "</ResourceRecordSet></Change></Changes></ChangeBatch></ChangeResourceRecordSetsRequest>";
}
}
@@ -0,0 +1,32 @@
package io.floci.aws.services.route53;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
class Route53RecordNameTest {
@ParameterizedTest
@CsvSource({"WWW.Example.TEST.,www.example.test", "*.Example.test.,\\052.example.test",
"\\052.Example.test,\\052.example.test", "\\101.Example.test.,a.example.test",
"a\\056b.Example.test.,a\\056b.example.test", "_Acme-Challenge.Example.test.,_acme-challenge.example.test",
"caf\u00e9.example.test,caf\\303\\251.example.test", "a\\400.example.test,a\\134400.example.test"})
void conditionNamesAreSpelledAsAwsNormalizesThem(String input, String expected) {
assertEquals(expected, Route53RecordName.conditionName(input));
}
@Test
void recordIdentityDecodesLettersAndKeepsWildcardsAndEscapedDots() {
assertEquals("a.example.test.", Route53RecordName.recordName("\\101.Example.test"));
assertEquals("*.example.test.", Route53RecordName.recordName("\\052.Example.test"));
assertEquals(Route53RecordName.recordName("*a.example.test"),
Route53RecordName.recordName("\\052a.example.test"));
assertNotEquals(Route53RecordName.recordName("a\\056b.example.test"),
Route53RecordName.recordName("a.b.example.test"));
assertEquals(Route53RecordName.recordName("caf\\303\\251.example.test"),
Route53RecordName.recordName("caf\u00e9.example.test"), "a byte given as its escape code is that byte");
}
}
@@ -215,7 +215,7 @@ class Route53ServiceTest {
lower.setType("AAAA");
assertFalse(Route53Service.sameRecord(upper, lower));
assertFalse(Route53Service.sameRecord(aRecord("Ä.example", 60), aRecord("ä.example", 60)));
assertFalse(Route53Service.sameRecord(aRecord("\\127.example", 60), aRecord("w.example", 60)));
assertTrue(Route53Service.sameRecord(aRecord("\\127.example", 60), aRecord("w.example", 60)));
}
@Test