From e2712cf344e2ca4f474ceee04a56f5c21f18013d Mon Sep 17 00:00:00 2001 From: luiseterc Date: Sat, 14 Nov 2026 17:13:47 +0100 Subject: [PATCH] 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 --- Makefile | 2 +- docs/services/iam.md | 11 + docs/services/route53.md | 6 + .../common/IamConditionContextResolver.java | 80 +++++- .../aws/core/common/RequestConditionKeys.java | 12 + .../core/common/RequestConditionSpelling.java | 21 ++ .../io/floci/aws/core/common/XmlParser.java | 42 ++++ .../services/route53/Route53Controller.java | 229 +++++++++--------- .../services/route53/Route53RecordName.java | 65 +++++ .../aws/services/route53/Route53Service.java | 25 +- .../resources/aws/request-condition-keys.json | 42 +++- .../IamConditionContextResolverTest.java | 69 +++++- ...oute53RecordConditionsIntegrationTest.java | 135 +++++++++++ .../dynamodb/backend/DynamoDbFacadeTest.java | 2 +- ...angeResourceRecordSetsIntegrationTest.java | 58 +++++ .../route53/Route53RecordNameTest.java | 32 +++ .../services/route53/Route53ServiceTest.java | 2 +- tools/aws/regen_request_condition_keys.py | 112 +++++++-- .../aws/test_regen_request_condition_keys.py | 57 ++++- 19 files changed, 846 insertions(+), 156 deletions(-) create mode 100644 src/main/java/io/floci/aws/core/common/RequestConditionSpelling.java create mode 100644 src/main/java/io/floci/aws/services/route53/Route53RecordName.java create mode 100644 src/test/java/io/floci/aws/core/common/Route53RecordConditionsIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/route53/Route53RecordNameTest.java diff --git a/Makefile b/Makefile index 10b5c8843a..368db76701 100644 --- a/Makefile +++ b/Makefile @@ -900,7 +900,7 @@ s3control-tag-condition-keys-verify: ## Check the S3 Control tag condition actio $(PYTHON) tools/aws/regen_s3control_tag_condition_keys.py --verify .PHONY: request-condition-keys-sync request-condition-keys-check request-condition-keys-verify -request-condition-keys-sync: ## Regenerate the Lambda Web and Redshift request condition keys from AWS and botocore +request-condition-keys-sync: ## Regenerate the Lambda Web, Redshift and Route 53 request condition keys from AWS and botocore $(PYTHON) tools/aws/regen_request_condition_keys.py request-condition-keys-check: ## Check the request condition key members against pinned botocore $(PYTHON) tools/aws/regen_request_condition_keys.py --check diff --git a/docs/services/iam.md b/docs/services/iam.md index 1d564baf35..c330134651 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3088,6 +3088,17 @@ floci populates: generates from the Service Reference and pinned botocore. Regenerate with `make request-condition-keys-sync`. `redshift:DbName` and `redshift:DurationSeconds` are not populated yet. +- `route53:ChangeResourceRecordSetsActions`, `route53:ChangeResourceRecordSetsRecordTypes` and + `route53:ChangeResourceRecordSetsNormalizedRecordNames`: the `Action`, `Type` and `Name` of every change + in a `ChangeResourceRecordSets` batch, each read from its own change or record set, so a `Name` elsewhere + in the record set is not read, and a second copy of one is refused with `InvalidInput`, as the change is. + A record name is spelled as the + [Route 53 condition format](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/specifying-conditions-route53.html) + gives it: lowercase, without the final dot, and with every character other than a to z, 0 to 9, hyphen, + underscore and the dots between labels as an octal escape code (`*` is `\052`). Use + `ForAllValues:StringEquals` with `Null` set to `false` to require every change to match. The actions, the + request members, their botocore shapes and the request protocol come from the same + `request-condition-keys.json`, and Route 53 spells the names as its `DNSName` shape. **Any other condition key is absent from the request context.** A positive scalar operator without `IfExists` on an absent key makes the whole statement *not apply*: it neither matches nor diff --git a/docs/services/route53.md b/docs/services/route53.md index eeb6c3233b..5755e95ed3 100644 --- a/docs/services/route53.md +++ b/docs/services/route53.md @@ -199,6 +199,12 @@ aws route53 delete-hosted-zone --id Z1PA6795UKMFR9 ``` Record names in change batches are stored with lowercase ASCII letters and a trailing dot. +As the [DNS domain name format](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DomainNameFormat.html) +describes, a letter given as an octal escape code (`\101`) is stored as that lowercase letter, and every +character other than a to z, 0 to 9, hyphen, underscore, `*` and the dots between labels as its escape code, so +`\101.example.com` and `a.example.com` name one record. Only the `Name`, `Type` and `Action` a record set or +change holds directly are read, and a second copy of any element a change or record set holds once is refused +with `InvalidInput`. CREATE, UPSERT, and DELETE use that name identity while keeping the record type and routing set identifier distinct. A case-only CloudFormation record-name update retains the record. DELETE still requires matching record values and routing properties. diff --git a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java index ef87c6c0c2..51420d265e 100644 --- a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java @@ -103,6 +103,7 @@ public class IamConditionContextResolver { private final Instance crossAccountService; private final Instance iamService; private final Instance lambdaWebService; + private final Instance requestConditionSpellings; private final RequestContext requestContext; private final EmulatorConfig config; private final CurrentVertxRequest currentVertxRequest; @@ -121,12 +122,13 @@ public class IamConditionContextResolver { Instance crossAccountService, Instance iamService, Instance lambdaWebService, + Instance requestConditionSpellings, RequestContext requestContext, EmulatorConfig config, CurrentVertxRequest currentVertxRequest, ResolvedServiceCatalog serviceCatalog) { this(dynamoDbFacade, ec2Service, s3Service, logsService, crossAccountService, iamService, - lambdaWebService, requestContext, + lambdaWebService, requestConditionSpellings, requestContext, config, currentVertxRequest, serviceCatalog, Clock.systemUTC()); } @@ -137,6 +139,7 @@ public class IamConditionContextResolver { Instance crossAccountService, Instance iamService, Instance lambdaWebService, + Instance requestConditionSpellings, RequestContext requestContext, EmulatorConfig config, CurrentVertxRequest currentVertxRequest, @@ -148,6 +151,7 @@ public class IamConditionContextResolver { this.crossAccountService = crossAccountService; this.iamService = iamService; this.lambdaWebService = lambdaWebService; + this.requestConditionSpellings = requestConditionSpellings; this.requestContext = requestContext; this.config = config; this.currentVertxRequest = currentVertxRequest; @@ -164,9 +168,7 @@ public class IamConditionContextResolver { case "iam" -> iamConditionContext(action, ctx); case "logs" -> logsConditionContext(action, ctx); case "lambda" -> lambdaConditionContext(action, ctx); - case "redshift" -> RequestConditionKeys.requestKeys(action).isEmpty() ? null - : requestConditions(action, formParameters(ctx)::get); - default -> null; + default -> requestMemberConditions(action, ctx); }; } @@ -322,20 +324,82 @@ public class IamConditionContextResolver { } /** - * The keys a request for {@code action} carries in its own members, such as a Redshift DbUser or an - * OpenTunnel remotePort, read through {@code parameter} from the table in - * {@code request-condition-keys.json}; null when it carries none. + * The keys a request for {@code action} carries in its own members, such as an OpenTunnel remotePort, read + * through {@code parameter} from the table in {@code request-condition-keys.json}; null when it carries none. */ static Map> requestConditions(String action, Function parameter) { + return requestConditions(action, member -> { + String value = parameter.apply(member); + return value == null ? List.of() : List.of(value); + }, null); + } + + /** + * The keys a request for {@code action} carries in its own members, such as a Redshift DbUser or the record names + * of a Route 53 change batch, read as its namespace's protocol carries them (a Query form, an XML body), from the + * table in {@code request-condition-keys.json}; null when it carries none, or is sent in a protocol no reader here + * reads yet. + */ + private Map> requestMemberConditions(String action, ContainerRequestContext ctx) { + List keys = RequestConditionKeys.requestKeys(action); + if (keys.isEmpty()) { + return null; + } + String namespace = action.substring(0, action.indexOf(':')); + String protocol = RequestConditionKeys.protocol(namespace); + Function> values; + if ("query".equals(protocol) || "ec2".equals(protocol)) { + Map form = formParameters(ctx); + values = member -> form.containsKey(member) ? List.of(form.get(member)) : List.of(); + } else if ("rest-xml".equals(protocol)) { + List members = keys.stream() + .flatMap(key -> RequestConditionKeys.members(action, key).stream()).toList(); + Map> read = XmlParser.valuesAt(bodyText(ctx), members); + if (read == null) { + // The handler refuses a body it cannot read the same elements from, so nothing is checked on it. + return null; + } + values = member -> read.getOrDefault(member, List.of()); + } else { + return null; + } + return requestConditions(action, values, requestConditionSpelling(namespace)); + } + + /** + * Every value {@code values} reads for each member the table names for each key {@code action} takes, spelled by + * {@code spelling} as the namespace's service spells the member's shape; null when there are none. + */ + private static Map> requestConditions(String action, Function> values, + RequestConditionSpelling spelling) { Map> conditions = new LinkedHashMap<>(); for (String key : RequestConditionKeys.requestKeys(action)) { for (String member : RequestConditionKeys.members(action, key)) { - putIfPresent(conditions, key, parameter.apply(member)); + String shape = RequestConditionKeys.shape(action, member); + for (String value : values.apply(member)) { + if (value != null && !value.isBlank()) { + conditions.computeIfAbsent(key, ignored -> new ArrayList<>()) + .add(spelling == null ? value : spelling.spell(shape, value)); + } + } } } return conditions.isEmpty() ? null : conditions; } + /** The registered spelling of the namespace's request members; null when there is none. */ + private RequestConditionSpelling requestConditionSpelling(String namespace) { + if (requestConditionSpellings == null || requestConditionSpellings.isUnsatisfied()) { + return null; + } + for (RequestConditionSpelling spelling : requestConditionSpellings) { + if (spelling.namespace().equals(namespace)) { + return spelling; + } + } + return null; + } + public static Map> withGlobalContext(Map> serviceContext, String resourceArn, String region, String accountId, String resourceOwnerAccountId) { diff --git a/src/main/java/io/floci/aws/core/common/RequestConditionKeys.java b/src/main/java/io/floci/aws/core/common/RequestConditionKeys.java index 8b1ce5299e..b49035c32c 100644 --- a/src/main/java/io/floci/aws/core/common/RequestConditionKeys.java +++ b/src/main/java/io/floci/aws/core/common/RequestConditionKeys.java @@ -47,4 +47,16 @@ final class RequestConditionKeys { TABLE.path("members").path(action).properties().forEach(key -> keys.add(key.getKey())); return keys; } + + /** The protocol a namespace's requests are sent in, as botocore gives it ({@code rest-xml}); null without one. */ + static String protocol(String namespace) { + JsonNode protocol = TABLE.path("protocols").path(namespace); + return protocol.isTextual() ? protocol.asText() : null; + } + + /** The botocore shape of the request member at {@code member} of {@code action}; null when the table has none. */ + static String shape(String action, String member) { + JsonNode shape = TABLE.path("memberShapes").path(action).path(member); + return shape.isTextual() ? shape.asText() : null; + } } diff --git a/src/main/java/io/floci/aws/core/common/RequestConditionSpelling.java b/src/main/java/io/floci/aws/core/common/RequestConditionSpelling.java new file mode 100644 index 0000000000..4067bd6261 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/RequestConditionSpelling.java @@ -0,0 +1,21 @@ +package io.floci.aws.core.common; + +/** + * Spells a value a request member carries the way its service spells the member's botocore shape, for the condition + * keys IAM reads from request members (Route 53 spells a {@code DNSName} as its record names are spelled, so + * {@code route53:ChangeResourceRecordSetsNormalizedRecordNames} carries the name as AWS normalizes it). + * + *

Implemented by the service whose shapes have a spelling of their own; looked up lazily by + * {@code IamConditionContextResolver} through {@code Instance} for the namespace a request + * is of, so IAM never depends on that service directly. Which keys an action takes, which members carry them and the + * members' shapes all come from the generated {@code request-condition-keys.json}: a spelling only answers for the + * shape the table gives, never for a key or an action.

+ */ +public interface RequestConditionSpelling { + + /** The namespace of the requests whose members it spells, as the table names it ({@code route53}). */ + String namespace(); + + /** {@code value} as the service spells a member of {@code shape}; {@code value} itself for a shape it does not. */ + String spell(String shape, String value); +} diff --git a/src/main/java/io/floci/aws/core/common/XmlParser.java b/src/main/java/io/floci/aws/core/common/XmlParser.java index 6953d731c4..4b1dc518e2 100644 --- a/src/main/java/io/floci/aws/core/common/XmlParser.java +++ b/src/main/java/io/floci/aws/core/common/XmlParser.java @@ -13,6 +13,7 @@ import java.io.ByteArrayInputStream; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -134,6 +135,47 @@ public final class XmlParser { return root; } + /** + * The text of every element at each of {@code paths}, in document order. A path names elements by their local + * names below the root element, joined by dots ({@code ChangeBatch.Changes.Change.Action}), so an element of the + * same name elsewhere is not read. Null when the body is empty or does not parse, or when an element at a path + * holds elements rather than text, which a handler reading it with {@link XMLStreamReader#getElementText} + * refuses too. + */ + public static Map> valuesAt(String xml, Collection paths) { + if (xml == null || xml.isEmpty()) { + return null; + } + Map> values = new LinkedHashMap<>(); + List open = new ArrayList<>(); + boolean rootOpen = false; + try { + XMLStreamReader r = FACTORY.createXMLStreamReader(new StringReader(xml)); + while (r.hasNext()) { + int event = r.next(); + if (event == XMLStreamConstants.START_ELEMENT) { + if (!rootOpen) { + rootOpen = true; + continue; + } + open.add(r.getLocalName()); + String path = String.join(".", open); + if (paths.contains(path)) { + values.computeIfAbsent(path, ignored -> new ArrayList<>()).add(r.getElementText()); + open.removeLast(); + } + } else if (event == XMLStreamConstants.END_ELEMENT && !open.isEmpty()) { + open.removeLast(); + } + } + r.close(); + } catch (Exception e) { + LOG.debugv("Ignoring malformed XML during parse: {0}", e.getMessage()); + return null; + } + return values; + } + /** * Extracts the text content of every element whose local name matches {@code elementName}. * diff --git a/src/main/java/io/floci/aws/services/route53/Route53Controller.java b/src/main/java/io/floci/aws/services/route53/Route53Controller.java index 02d7f03f47..344b18fed8 100644 --- a/src/main/java/io/floci/aws/services/route53/Route53Controller.java +++ b/src/main/java/io/floci/aws/services/route53/Route53Controller.java @@ -29,8 +29,11 @@ import javax.xml.stream.XMLStreamReader; import java.net.URI; import java.time.Instant; +import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Deque; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -42,6 +45,15 @@ public class Route53Controller { private static final String XML = "application/xml"; private static final Set CHANGE_ACTIONS = Set.of("CREATE", "DELETE", "UPSERT"); + /** Where a change batch's elements sit below the request's root, as Route 53's schema nests them. */ + private static final String CHANGES = "ChangeBatch/Changes"; + private static final String CHANGE = CHANGES + "/Change"; + private static final String RECORD_SET = CHANGE + "/ResourceRecordSet"; + private static final String RESOURCE_RECORD = RECORD_SET + "/ResourceRecords/ResourceRecord"; + private static final String ALIAS_TARGET = RECORD_SET + "/AliasTarget"; + private static final Set RECORD_SET_TEXT = Set.of("Name", "Type", "TTL", "SetIdentifier", + "MultiValueAnswer", "Weight", "Region", "Failover", "HealthCheckId"); + private static final Set ALIAS_TARGET_TEXT = Set.of("HostedZoneId", "DNSName", "EvaluateTargetHealth"); @Inject Route53Service service; @@ -1013,163 +1025,120 @@ public class Route53Controller { return result; } + /** + * Reads each element only where Route 53's schema puts it below the request's root, so an element of the same + * name anywhere else (a {@code Name} inside a {@code GeoLocation}) is skipped, and refuses a second copy of an + * element a change, record set or alias target holds once. IAM reads the batch's condition keys from these same + * elements, through the request members the generated condition key table names, so both read one batch. + */ private void parseChangeBatchInto(String body, List> result) { try { XMLStreamReader r = XmlParser.newStreamReader(body); + Deque open = new ArrayDeque<>(); + boolean rootOpen = false; String currentAction = null; ResourceRecordSet currentRrs = null; List currentRecords = null; AliasTarget currentAlias = null; - int depth = 0; - String currentElement = null; - boolean inChangeBatch = false; - boolean inChange = false; - boolean inRrs = false; - boolean inResourceRecords = false; - boolean inAlias = false; - boolean inHealthCheckConfig = false; + Set changeRead = new HashSet<>(); + Set recordSetRead = new HashSet<>(); + Set aliasRead = new HashSet<>(); while (r.hasNext()) { int event = r.next(); if (event == XMLStreamConstants.START_ELEMENT) { - currentElement = r.getLocalName(); - switch (currentElement) { - case "ChangeBatch" -> inChangeBatch = true; - case "Change" -> { - if (inChangeBatch) { - inChange = true; + if (!rootOpen) { + rootOpen = true; + continue; + } + String name = r.getLocalName(); + switch (String.join("/", open)) { + case CHANGES -> { + if ("Change".equals(name)) { currentAction = null; currentRrs = null; + currentRecords = null; + changeRead.clear(); } } - case "Action" -> { - if (inChange && !inRrs) { + case CHANGE -> { + if ("Action".equals(name)) { + readOnce(changeRead, name); currentAction = r.getElementText(); if (!CHANGE_ACTIONS.contains(currentAction)) { throw new AwsException("InvalidInput", "Invalid value '" + currentAction + "' at 'Action' failed to satisfy " + "constraint: Member must satisfy enum value set.", 400); } + continue; } - } - case "ResourceRecordSet" -> { - if (inChange) { - inRrs = true; + if ("ResourceRecordSet".equals(name)) { + readOnce(changeRead, name); currentRrs = new ResourceRecordSet(); currentRecords = new ArrayList<>(); + recordSetRead.clear(); } } - case "ResourceRecords" -> { if (inRrs) inResourceRecords = true; } - case "AliasTarget" -> { - if (inRrs) { - inAlias = true; + case RECORD_SET -> { + if (RECORD_SET_TEXT.contains(name)) { + readOnce(recordSetRead, name); + readRecordSetText(currentRrs, name, r.getElementText()); + continue; + } + if ("ResourceRecords".equals(name)) { + readOnce(recordSetRead, name); + } else if ("AliasTarget".equals(name)) { + readOnce(recordSetRead, name); currentAlias = new AliasTarget(); + aliasRead.clear(); } } - case "Name" -> { - if (inRrs && !inAlias) { - String n = r.getElementText(); - if (n != null && !n.endsWith(".")) n = n + "."; - if (currentRrs != null) currentRrs.setName(n); - } - } - case "Type" -> { - if (inRrs && !inAlias && !inHealthCheckConfig && currentRrs != null) { - currentRrs.setType(r.getElementText()); - } - } - case "TTL" -> { - if (inRrs && currentRrs != null) { - String ttl = r.getElementText(); - try { - currentRrs.setTtl(Long.parseLong(ttl)); - } catch (NumberFormatException e) { - throw new AwsException("InvalidInput", - "Invalid value '" + ttl + "' at 'TTL' failed to satisfy constraint: " - + "Member must be a valid long.", 400); - } - } - } - case "Value" -> { - if (inResourceRecords && currentRecords != null) { + case RESOURCE_RECORD -> { + if ("Value".equals(name)) { currentRecords.add(new ResourceRecord(r.getElementText())); + continue; } } - case "SetIdentifier" -> { - if (inRrs && currentRrs != null) currentRrs.setSetIdentifier(r.getElementText()); - } - case "MultiValueAnswer" -> { - if (inRrs && currentRrs != null) { - String multiValueAnswer = r.getElementText(); - if (!"true".equals(multiValueAnswer) && !"false".equals(multiValueAnswer)) { - throw new AwsException("InvalidInput", - "MultiValueAnswer must be true or false.", 400); + case ALIAS_TARGET -> { + if (ALIAS_TARGET_TEXT.contains(name)) { + readOnce(aliasRead, name); + String text = r.getElementText(); + switch (name) { + case "HostedZoneId" -> currentAlias.setHostedZoneId(text); + case "DNSName" -> currentAlias.setDnsName(text); + default -> currentAlias.setEvaluateTargetHealth("true".equalsIgnoreCase(text)); } - currentRrs.setMultiValueAnswer(Boolean.valueOf(multiValueAnswer)); + continue; } } - case "Weight" -> { - if (inRrs && currentRrs != null) { - String weight = r.getElementText(); - try { - currentRrs.setWeight(Long.parseLong(weight)); - } catch (NumberFormatException e) { - throw new AwsException("InvalidInput", - "Invalid value '" + weight + "' at 'Weight' failed to satisfy " - + "constraint: Member must be a valid long.", 400); - } - } - } - case "Region" -> { - if (inRrs && !inAlias && currentRrs != null) currentRrs.setRegion(r.getElementText()); - } - case "Failover" -> { - if (inRrs && currentRrs != null) currentRrs.setFailover(r.getElementText()); - } - case "HealthCheckId" -> { - if (inRrs && !inHealthCheckConfig && currentRrs != null) { - currentRrs.setHealthCheckId(r.getElementText()); - } - } - case "HostedZoneId" -> { - if (inAlias && currentAlias != null) currentAlias.setHostedZoneId(r.getElementText()); - } - case "DNSName" -> { - if (inAlias && currentAlias != null) currentAlias.setDnsName(r.getElementText()); - } - case "EvaluateTargetHealth" -> { - if (inAlias && currentAlias != null) { - currentAlias.setEvaluateTargetHealth( - "true".equalsIgnoreCase(r.getElementText())); - } + default -> { } } - } else if (event == XMLStreamConstants.END_ELEMENT) { - switch (r.getLocalName()) { - case "ResourceRecords" -> inResourceRecords = false; - case "AliasTarget" -> { - if (inAlias && currentRrs != null && currentAlias != null) { + open.addLast(name); + } else if (event == XMLStreamConstants.END_ELEMENT && !open.isEmpty()) { + String name = open.pollLast(); + switch (String.join("/", open)) { + case RECORD_SET -> { + if ("AliasTarget".equals(name)) { currentRrs.setAliasTarget(currentAlias); + currentAlias = null; } - inAlias = false; - currentAlias = null; } - case "ResourceRecordSet" -> { - if (inRrs && currentRrs != null) { + case CHANGE -> { + if ("ResourceRecordSet".equals(name)) { if (currentRrs.getName() == null || currentRrs.getType() == null) { throw new AwsException("InvalidInput", "ResourceRecordSet is missing a required Name or Type element.", 400); } - boolean hasRecords = currentRecords != null && !currentRecords.isEmpty(); + boolean hasRecords = !currentRecords.isEmpty(); if (hasRecords) { currentRrs.setRecords(currentRecords); } requireExactlyOneRecordShape(currentAction, currentRrs, hasRecords); } - inRrs = false; } - case "Change" -> { - if (inChange) { + case CHANGES -> { + if ("Change".equals(name)) { if (currentAction == null || currentRrs == null) { throw new AwsException("InvalidInput", "Change is missing a required Action or ResourceRecordSet element.", @@ -1179,11 +1148,12 @@ public class Route53Controller { change.put("action", currentAction); change.put("rrs", currentRrs); result.add(change); + currentAction = null; + currentRrs = null; + currentRecords = null; } - inChange = false; - currentAction = null; - currentRrs = null; - currentRecords = null; + } + default -> { } } } @@ -1196,6 +1166,43 @@ public class Route53Controller { } } + /** Sets the record set's {@code element} from its text, refusing a TTL, weight or answer flag that is not one. */ + private static void readRecordSetText(ResourceRecordSet rrs, String element, String text) { + switch (element) { + case "Name" -> rrs.setName(text.endsWith(".") ? text : text + "."); + case "Type" -> rrs.setType(text); + case "TTL" -> rrs.setTtl(longElement(element, text)); + case "SetIdentifier" -> rrs.setSetIdentifier(text); + case "MultiValueAnswer" -> { + if (!"true".equals(text) && !"false".equals(text)) { + throw new AwsException("InvalidInput", "MultiValueAnswer must be true or false.", 400); + } + rrs.setMultiValueAnswer(Boolean.valueOf(text)); + } + case "Weight" -> rrs.setWeight(longElement(element, text)); + case "Region" -> rrs.setRegion(text); + case "Failover" -> rrs.setFailover(text); + default -> rrs.setHealthCheckId(text); + } + } + + private static long longElement(String element, String text) { + try { + return Long.parseLong(text); + } catch (NumberFormatException e) { + throw new AwsException("InvalidInput", "Invalid value '" + text + "' at '" + element + + "' failed to satisfy constraint: Member must be a valid long.", 400); + } + } + + /** Records {@code element} as read in the element holding it, refusing a second copy, as Route 53's schema does. */ + private static void readOnce(Set read, String element) { + if (!read.add(element)) { + throw new AwsException("InvalidInput", "Invalid XML ; cvc-complex-type.2.4.a: Invalid content was found " + + "starting with element '{\"" + NS + "\":" + element + "}'.", 400); + } + } + private HealthCheckConfig parseHealthCheckConfig(String body) { HealthCheckConfig cfg = new HealthCheckConfig(); cfg.setType(XmlParser.extractFirst(body, "Type", null)); diff --git a/src/main/java/io/floci/aws/services/route53/Route53RecordName.java b/src/main/java/io/floci/aws/services/route53/Route53RecordName.java new file mode 100644 index 0000000000..b3fa3c2873 --- /dev/null +++ b/src/main/java/io/floci/aws/services/route53/Route53RecordName.java @@ -0,0 +1,65 @@ +package io.floci.aws.services.route53; + +import java.nio.charset.StandardCharsets; +import java.util.Locale; + +/** + * A DNS name as Route 53 spells it (Route 53 Developer Guide, "DNS domain name format"): letters lowercase however + * they were given, as letters or as escape codes, and every byte other than a to z, 0 to 9, hyphen, underscore and + * the dot between labels as a three-digit octal escape code. A record's identity and the record names IAM reads as + * condition values both take this spelling, so a name given in escape codes names the record its letters name. + */ +public final class Route53RecordName { + + private Route53RecordName() {} + + /** + * The name as {@code route53:ChangeResourceRecordSetsNormalizedRecordNames} carries it (Route 53 Developer Guide, + * "Normalizing the Route 53 condition key values"): without the final dot, and with {@code *} as {@code \052}. + */ + public static String conditionName(String name) { + return spell(name, false); + } + + /** + * The name a record is stored and matched under: with the final dot, and with {@code *} kept as given, the + * spelling Floci's DNS server matches wildcard records by. + */ + public static String recordName(String name) { + if (name == null || name.isEmpty()) { + return name; + } + return spell(name, true) + "."; + } + + private static String spell(String name, boolean literalAsterisk) { + String source = name.endsWith(".") ? name.substring(0, name.length() - 1) : name; + byte[] bytes = source.getBytes(StandardCharsets.UTF_8); + StringBuilder spelled = new StringBuilder(bytes.length); + for (int index = 0; index < bytes.length; index++) { + int value = bytes[index] & 0xFF; + boolean escaped = value == '\\' && isEscapeCode(bytes, index + 1); + if (escaped) { + value = (bytes[index + 1] - '0') * 64 + (bytes[index + 2] - '0') * 8 + (bytes[index + 3] - '0'); + index += 3; + } + if (value >= 'A' && value <= 'Z') { + value += 'a' - 'A'; + } + if (value >= 'a' && value <= 'z' || value >= '0' && value <= '9' || value == '-' || value == '_' + || value == '*' && literalAsterisk || value == '.' && !escaped) { + spelled.append((char) value); + } else { + spelled.append(String.format(Locale.ROOT, "\\%03o", value)); + } + } + return spelled.toString(); + } + + /** Whether the three bytes from {@code start} are the octal digits of a byte, {@code 000} to {@code 377}. */ + private static boolean isEscapeCode(byte[] bytes, int start) { + return start + 2 < bytes.length && bytes[start] >= '0' && bytes[start] <= '3' + && bytes[start + 1] >= '0' && bytes[start + 1] <= '7' + && bytes[start + 2] >= '0' && bytes[start + 2] <= '7'; + } +} 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 a7f0bf59e9..5856e78b2d 100644 --- a/src/main/java/io/floci/aws/services/route53/Route53Service.java +++ b/src/main/java/io/floci/aws/services/route53/Route53Service.java @@ -5,6 +5,7 @@ import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsException; 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.DnsLookupHelper; import io.floci.aws.core.storage.AccountAwareStorageBackend; @@ -40,7 +41,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; @ApplicationScoped -public class Route53Service implements Resettable { +public class Route53Service implements Resettable, RequestConditionSpelling { private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; private static final SecureRandom RANDOM = new SecureRandom(); @@ -1114,15 +1115,7 @@ public class Route53Service implements Resettable { } public static String normalizeRecordName(String name) { - String normalized = normalizeName(name); - if (normalized == null) { - return null; - } - StringBuilder result = new StringBuilder(normalized.length()); - for (int i = 0; i < normalized.length(); i++) { - result.append(asciiLower(normalized.charAt(i))); - } - return result.toString(); + return Route53RecordName.recordName(name); } private static String generateZoneId() { @@ -1308,4 +1301,16 @@ public class Route53Service implements Resettable { privateZoneNameCounts.clear(); publicZoneNameCounts.clear(); } + + /** The namespace whose request members this spells, as the generated condition key table names it. */ + @Override + public String namespace() { + return "route53"; + } + + /** A {@code DNSName} as a record name is spelled for a condition key; a member of any other shape as given. */ + @Override + public String spell(String shape, String value) { + return "DNSName".equals(shape) ? Route53RecordName.conditionName(value) : value; + } } diff --git a/src/main/resources/aws/request-condition-keys.json b/src/main/resources/aws/request-condition-keys.json index 0671c1f2f6..ec0d9a732a 100644 --- a/src/main/resources/aws/request-condition-keys.json +++ b/src/main/resources/aws/request-condition-keys.json @@ -3,7 +3,7 @@ "generator": "tools/aws/regen_request_condition_keys.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.118 (installed package)", - "note": "make request-condition-keys-check re-derives members from botocore; make request-condition-keys-verify checks actions against AWS." + "note": "make request-condition-keys-check re-derives members, their shapes and the protocols from botocore; make request-condition-keys-verify checks actions against AWS." }, "actions": { "ec2-instance-connect:OpenTunnel": [ @@ -35,6 +35,11 @@ ], "redshift:GetClusterCredentials": [ "redshift:DbUser" + ], + "route53:ChangeResourceRecordSets": [ + "route53:ChangeResourceRecordSetsActions", + "route53:ChangeResourceRecordSetsNormalizedRecordNames", + "route53:ChangeResourceRecordSetsRecordTypes" ] }, "members": { @@ -68,6 +73,41 @@ "redshift:DbUser": [ "DbUser" ] + }, + "route53:ChangeResourceRecordSets": { + "route53:ChangeResourceRecordSetsActions": [ + "ChangeBatch.Changes.Change.Action" + ], + "route53:ChangeResourceRecordSetsNormalizedRecordNames": [ + "ChangeBatch.Changes.Change.ResourceRecordSet.Name" + ], + "route53:ChangeResourceRecordSetsRecordTypes": [ + "ChangeBatch.Changes.Change.ResourceRecordSet.Type" + ] } + }, + "memberShapes": { + "lambda:CreateWebFunction": { + "endpointConfig.authType": "AuthType" + }, + "lambda:CreateWebFunctionEndpoint": { + "authType": "AuthType" + }, + "lambda:UpdateWebFunctionEndpoint": { + "authType": "AuthType" + }, + "redshift:GetClusterCredentials": { + "DbUser": "String" + }, + "route53:ChangeResourceRecordSets": { + "ChangeBatch.Changes.Change.Action": "ChangeAction", + "ChangeBatch.Changes.Change.ResourceRecordSet.Name": "DNSName", + "ChangeBatch.Changes.Change.ResourceRecordSet.Type": "RRType" + } + }, + "protocols": { + "lambda": "rest-json", + "redshift": "query", + "route53": "rest-xml" } } diff --git a/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java b/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java index 1606d7447b..7441df4273 100644 --- a/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java +++ b/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java @@ -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 = """ + + + UPSERTProbe.Example.testA + elsewhere.example.test + DELETEsecond.example.test. + TXT + + """; + + 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("")), "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 spellings(RequestConditionSpelling... spellings) { + Instance 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)); } diff --git a/src/test/java/io/floci/aws/core/common/Route53RecordConditionsIntegrationTest.java b/src/test/java/io/floci/aws/core/common/Route53RecordConditionsIntegrationTest.java new file mode 100644 index 0000000000..d30694fd35 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/Route53RecordConditionsIntegrationTest.java @@ -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 beforeInvalid = admin.listResourceRecordSets(r -> r.hostedZoneId(zone)) + .resourceRecordSets(); + given().port(endpoint.getPort()).header("Authorization", auth(credentials.accessKeyId(), "route53")) + .contentType("application/xml").body("") + .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 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 + "]}"); + } +} diff --git a/src/test/java/io/floci/aws/services/dynamodb/backend/DynamoDbFacadeTest.java b/src/test/java/io/floci/aws/services/dynamodb/backend/DynamoDbFacadeTest.java index a2cc000112..1ec245e348 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/backend/DynamoDbFacadeTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/backend/DynamoDbFacadeTest.java @@ -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)); diff --git a/src/test/java/io/floci/aws/services/route53/Route53ChangeResourceRecordSetsIntegrationTest.java b/src/test/java/io/floci/aws/services/route53/Route53ChangeResourceRecordSetsIntegrationTest.java index 230ba47939..cc2ebba916 100644 --- a/src/test/java/io/floci/aws/services/route53/Route53ChangeResourceRecordSetsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/route53/Route53ChangeResourceRecordSetsIntegrationTest.java @@ -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 = + "300192.0.2.1"; @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("CREATE", "kept.nested-name.example.com.A" + + "other.nested-name.example.com." + 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 repeatedElementCases() { + String recordSet = "allowed.repeated.example.com.A" + A_RECORDS; + return Stream.of( + Arguments.of("Name", "CREATE", recordSet + + "other.repeated.example.com."), + Arguments.of("Action", "CREATEDELETE", recordSet), + Arguments.of("ResourceRecordSet", "CREATE" + + "other.repeated.example.com.A" + A_RECORDS + + "", 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 "" + + "" + change + "" + recordSet + + ""; + } } diff --git a/src/test/java/io/floci/aws/services/route53/Route53RecordNameTest.java b/src/test/java/io/floci/aws/services/route53/Route53RecordNameTest.java new file mode 100644 index 0000000000..18700b3469 --- /dev/null +++ b/src/test/java/io/floci/aws/services/route53/Route53RecordNameTest.java @@ -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"); + } +} 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 1356560abc..1ea37211cb 100644 --- a/src/test/java/io/floci/aws/services/route53/Route53ServiceTest.java +++ b/src/test/java/io/floci/aws/services/route53/Route53ServiceTest.java @@ -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 diff --git a/tools/aws/regen_request_condition_keys.py b/tools/aws/regen_request_condition_keys.py index d339bfb2d1..0d6f21a175 100644 --- a/tools/aws/regen_request_condition_keys.py +++ b/tools/aws/regen_request_condition_keys.py @@ -15,6 +15,10 @@ it. `SERVICES` names, for each namespace, the keys read and where: Service Reference spells the action's third key `MaxTunnelDuration`; IAM keys are case-insensitive). botocore does not model OpenTunnel (it is a WebSocket upgrade, not an API operation), so `SERVICES` gives its members itself (`"model": None`) and `--check` has no botocore model to compare them to. +- `route53`: a ChangeResourceRecordSets request is checked with every change's action, record type and record + name as `route53:ChangeResourceRecordSetsActions`, `...RecordTypes` and `...NormalizedRecordNames`. The names + are read as `DNSName` members, which Route 53 spells as AWS normalizes them for the key, through the spelling + the service registers for that shape. The table comes from two sources: @@ -27,10 +31,14 @@ The table comes from two sources: gives where each request carries the value. `actions` holds every action that takes a key a namespace reads, with the ones it takes. `members` holds, for -every action and key read from the request, the paths of the request members named as `SERVICES` gives, -dotted for a nested one; a Query request is read as a flat form, so its member must be top-level. A key read -from the stored resource has no member, and an action whose request does not carry the key is in -`not_in_request`, with the reason. +every action and key read from the request, the paths of the request members named as `SERVICES` gives, as the +request carries them: dotted for a nested one, `*` for each element of a list or map in a JSON body, and in an XML +body the elements botocore names, a list's own by the name of its member (`ChangeBatch.Changes.Change.Action`). +A Query request is read as a flat form, so its member must be top-level; an XML request is read from its body, so +its member must not be in the URI or a header, nor reached through a map or a flattened list. A key read from the +stored resource has no member, and an action whose request does not carry the key is in `not_in_request`, with +the reason. `memberShapes` gives each member's botocore shape, which a service may spell its own way (Route 53's +`DNSName`), and `protocols` each modelled namespace's protocol, which says how its requests are read. The two gates split along the sources: @@ -88,6 +96,14 @@ SERVICES = { "of its own request", }, }, + "route53": { + "model": "route53", + "request": {"route53:ChangeResourceRecordSetsActions": "Action", + "route53:ChangeResourceRecordSetsNormalizedRecordNames": "Name", + "route53:ChangeResourceRecordSetsRecordTypes": "Type"}, + "stored": (), + "not_in_request": {}, + }, } @@ -111,9 +127,27 @@ def action_keys(namespace: str, reference: dict) -> dict[str, list[str]]: def request_members(namespace: str, model: dict | None, actions: dict[str, list[str]]) -> dict[str, dict[str, list[str]]]: """For every action of the namespace and key read from its request, where the request carries the value.""" - service = SERVICES[namespace] - flat = model is not None and model.get("metadata", {}).get("protocol") in FLAT_PROTOCOLS found = {} + for action, key, path, _ in _located(namespace, model, actions): + found.setdefault(action, {}).setdefault(key, []).append(path) + return found + + +def member_shapes(namespace: str, model: dict | None, + actions: dict[str, list[str]]) -> dict[str, dict[str, str]]: + """For every action of the namespace, the botocore shape of each request member a key is read from.""" + found = {} + for action, _, path, shape in _located(namespace, model, actions): + if shape is not None: + found.setdefault(action, {})[path] = shape + return found + + +def _located(namespace: str, model: dict | None, actions: dict[str, list[str]]): + """Each (action, key, path, shape) of a key the namespace reads from its requests, the path as `members` gives + it and the shape botocore gives the member (None for a namespace botocore does not model).""" + service = SERVICES[namespace] + protocol = model.get("metadata", {}).get("protocol") if model is not None else None for action, keys in sorted(actions.items()): if not action.startswith(f"{namespace}:"): continue @@ -122,7 +156,7 @@ def request_members(namespace: str, model: dict | None, continue name = service["request"][key] if model is None: # not modelled by botocore: the member is the name SERVICES gives - found.setdefault(action, {})[key] = [name] + yield action, key, name, None continue operation = model["operations"].get(action.split(":", 1)[1]) if operation is None or "input" not in operation: @@ -130,11 +164,36 @@ def request_members(namespace: str, model: dict | None, paths = member_paths(model, operation["input"]["shape"], {name}) if not paths: raise ValueError(f"{action} takes {key} but its request has no {name} member") - nested = [path for path in paths if flat and "." in path] + nested = [path for path in paths if protocol in FLAT_PROTOCOLS and "." in path] if nested: raise ValueError(f"{action} takes {key} from {', '.join(nested)}, which a flat form does not carry") - found.setdefault(action, {})[key] = paths - return found + for path in paths: + carried, shape = carried_member(model, operation["input"]["shape"], path, protocol == "rest-xml") + yield action, key, carried, shape + + +def carried_member(model: dict, shape: str, path: str, xml: bool) -> tuple[str, str]: + """The member at `path`, as `member_paths` spells it, as the request carries it, with its botocore shape: the + same path in a form or a JSON body; in an XML body the elements botocore names, a list's own by the name of its + member. An XML body is read from its elements alone, so a member in the URI or a header, or one reached through a + map or a flattened list, which do not nest as these paths do, fails rather than being read wrong.""" + steps = [] + for index, step in enumerate(path.split(".")): + spec = model["shapes"][shape] + if step == "*": + element = spec.get("member") or spec["value"] + if xml and ("member" not in spec or spec.get("flattened")): + raise ValueError(f"{path} reaches the elements of a map or a flattened list, " + "which the XML reader does not read") + steps.append(element.get("locationName", "member") if xml else "*") + shape = element["shape"] + continue + member = spec["members"][step] + if xml and index == 0 and "location" in member: + raise ValueError(f"{path} is carried in the {member['location']}, which the XML reader does not read") + steps.append(member.get("locationName", step) if xml else step) + shape = member["shape"] + return ".".join(steps), shape def render(document: dict) -> str: @@ -158,6 +217,14 @@ def validate(document: dict) -> list[str]: problems.append("redshift:GetClusterCredentials does not read redshift:DbUser from DbUser") if members.get("ec2-instance-connect:OpenTunnel", {}).get("ec2-instance-connect:remotePort") != ["remotePort"]: problems.append("ec2-instance-connect:OpenTunnel does not read ec2-instance-connect:remotePort from remotePort") + record_name = "ChangeBatch.Changes.Change.ResourceRecordSet.Name" + if members.get("route53:ChangeResourceRecordSets", {}).get( + "route53:ChangeResourceRecordSetsNormalizedRecordNames") != [record_name]: + problems.append("route53:ChangeResourceRecordSets does not read its record names from " + record_name) + if document.get("memberShapes", {}).get("route53:ChangeResourceRecordSets", {}).get(record_name) != "DNSName": + problems.append(f"route53:ChangeResourceRecordSets does not give {record_name} the shape DNSName") + if document.get("protocols", {}).get("route53") != "rest-xml": + problems.append("route53 is not read as rest-xml") return problems @@ -177,12 +244,17 @@ def _actions(source_dir: Path | None) -> dict[str, list[str]]: def _members(actions: dict[str, list[str]], botocore_data: Path | None) -> tuple[dict, str]: + """The `members`, `memberShapes` and `protocols` sections botocore gives, and its provenance.""" data, provenance = resolve_botocore_data(botocore_data) - members = {} + members, shapes, protocols = {}, {}, {} for namespace, service in SERVICES.items(): model = service["model"] and load_model(latest_model_dir(data, service["model"])) members.update(request_members(namespace, model, actions)) - return dict(sorted(members.items())), provenance + shapes.update(member_shapes(namespace, model, actions)) + if model: + protocols[namespace] = model["metadata"]["protocol"] + return {"members": dict(sorted(members.items())), "memberShapes": dict(sorted(shapes.items())), + "protocols": dict(sorted(protocols.items()))}, provenance def main(argv: list[str] | None = None) -> int: @@ -197,9 +269,10 @@ def main(argv: list[str] | None = None) -> int: document = json.loads(OUTPUT.read_text(encoding="utf-8")) problems = validate(document) if args.check and not problems: - members, provenance = _members(document["actions"], args.botocore_data) - if document["members"] != members: - problems.append(f"members differ from {provenance}") + sections, provenance = _members(document["actions"], args.botocore_data) + for section, expected in sections.items(): + if document.get(section) != expected: + problems.append(f"{section} differ from {provenance}") if args.verify and document.get("actions") != _actions(args.source_dir): problems.append("actions differ from the AWS Service Reference") for problem in problems: @@ -207,12 +280,13 @@ def main(argv: list[str] | None = None) -> int: return 1 if problems else 0 actions = _actions(args.source_dir) - members, provenance = _members(actions, args.botocore_data) + sections, provenance = _members(actions, args.botocore_data) document = {"_source": {"generator": "tools/aws/regen_request_condition_keys.py", "reference": REFERENCE, "botocore": provenance, - "note": "make request-condition-keys-check re-derives members from botocore; " - "make request-condition-keys-verify checks actions against AWS."}, - "actions": actions, "members": members} + "note": "make request-condition-keys-check re-derives members, their shapes and the " + "protocols from botocore; make request-condition-keys-verify checks actions " + "against AWS."}, + "actions": actions, **sections} problems = validate(document) if problems: for problem in problems: diff --git a/tools/aws/test_regen_request_condition_keys.py b/tools/aws/test_regen_request_condition_keys.py index 20e78eae63..215d09f673 100644 --- a/tools/aws/test_regen_request_condition_keys.py +++ b/tools/aws/test_regen_request_condition_keys.py @@ -4,7 +4,7 @@ import subprocess import pytest -from regen_request_condition_keys import OUTPUT, action_keys, request_members, validate +from regen_request_condition_keys import OUTPUT, action_keys, member_shapes, request_members, validate def test_resource_and_action_keys_are_combined(): @@ -70,7 +70,55 @@ def test_a_nested_member_of_a_query_request_fails(): request_members("redshift", model, {"redshift:GetClusterCredentials": ["redshift:DbUser"]}) -def test_the_vendored_table_covers_both_namespaces(): +def xml_model(location=None, flattened=False): + """A REST-XML request whose list names its elements, as Route 53's change batch does.""" + batch = {"shape": "Batch", **({"location": location} if location else {})} + return {"metadata": {"protocol": "rest-xml"}, + "operations": {"ChangeResourceRecordSets": {"input": {"shape": "Input"}}}, "shapes": { + "Input": {"members": {"ChangeBatch": batch}}, + "Batch": {"members": {"Changes": {"shape": "Changes"}}}, + "Changes": {"type": "list", "member": {"shape": "Change", "locationName": "Change"}, + **({"flattened": True} if flattened else {})}, + "Change": {"members": {"Action": {"shape": "ChangeAction"}, + "ResourceRecordSet": {"shape": "Record"}}}, + "Record": {"members": {"Name": {"shape": "DNSName"}, "Type": {"shape": "RRType"}}}, + "ChangeAction": {}, "DNSName": {}, "RRType": {}}} + + +ROUTE53_ACTIONS = {"route53:ChangeResourceRecordSets": ["route53:ChangeResourceRecordSetsActions", + "route53:ChangeResourceRecordSetsNormalizedRecordNames", + "route53:ChangeResourceRecordSetsRecordTypes"]} + + +def test_an_xml_member_is_carried_by_its_elements_with_its_shape(): + assert request_members("route53", xml_model(), ROUTE53_ACTIONS) == {"route53:ChangeResourceRecordSets": { + "route53:ChangeResourceRecordSetsActions": ["ChangeBatch.Changes.Change.Action"], + "route53:ChangeResourceRecordSetsNormalizedRecordNames": ["ChangeBatch.Changes.Change.ResourceRecordSet.Name"], + "route53:ChangeResourceRecordSetsRecordTypes": ["ChangeBatch.Changes.Change.ResourceRecordSet.Type"]}} + assert member_shapes("route53", xml_model(), ROUTE53_ACTIONS) == {"route53:ChangeResourceRecordSets": { + "ChangeBatch.Changes.Change.Action": "ChangeAction", + "ChangeBatch.Changes.Change.ResourceRecordSet.Name": "DNSName", + "ChangeBatch.Changes.Change.ResourceRecordSet.Type": "RRType"}} + + +def test_a_json_member_keeps_its_member_names_and_has_a_shape(): + model = {"metadata": {"protocol": "rest-json"}, + "operations": {"CreateWebFunctionEndpoint": {"input": {"shape": "Input"}}}, + "shapes": {"Input": {"members": {"authType": {"shape": "AuthType"}}}, "AuthType": {}}} + assert member_shapes("lambda", model, {"lambda:CreateWebFunctionEndpoint": [ + "lambda:Request/WebFunctionAuthType"]}) == {"lambda:CreateWebFunctionEndpoint": {"authType": "AuthType"}} + + +@pytest.mark.parametrize("model, problem", [ + (xml_model(location="uri"), "carried in the uri"), + (xml_model(flattened=True), "a map or a flattened list"), +]) +def test_an_xml_member_the_body_does_not_nest_fails(model, problem): + with pytest.raises(ValueError, match=problem): + request_members("route53", model, ROUTE53_ACTIONS) + + +def test_the_vendored_table_covers_its_namespaces(): document = json.loads(OUTPUT.read_text()) assert validate(document) == [] assert document["actions"]["lambda:UpdateWebFunctionEndpoint"] == [ @@ -80,6 +128,11 @@ def test_the_vendored_table_covers_both_namespaces(): assert document["actions"]["redshift:CreateClusterUser"] == ["redshift:DbUser"] assert "redshift:CreateClusterUser" not in document["members"] assert document["members"]["redshift:GetClusterCredentials"] == {"redshift:DbUser": ["DbUser"]} + assert document["actions"]["route53:ChangeResourceRecordSets"] == ROUTE53_ACTIONS[ + "route53:ChangeResourceRecordSets"] + assert document["memberShapes"]["route53:ChangeResourceRecordSets"][ + "ChangeBatch.Changes.Change.ResourceRecordSet.Name"] == "DNSName" + assert document["protocols"] == {"lambda": "rest-json", "redshift": "query", "route53": "rest-xml"} @pytest.mark.parametrize("changed", [