diff --git a/.github/workflows/iam-data-drift.yml b/.github/workflows/iam-data-drift.yml index 31d850d864..3f9fafce1d 100644 --- a/.github/workflows/iam-data-drift.yml +++ b/.github/workflows/iam-data-drift.yml @@ -100,6 +100,9 @@ on: - 'tools/aws/sources/eks-condition-keys.json' - 'tools/aws/fetch_eks_conditions.py' - 'tools/aws/test_fetch_eks_conditions.py' + - 'tools/aws/sources/route53-condition-keys.json' + - 'tools/aws/fetch_route53_conditions.py' + - 'tools/aws/test_fetch_route53_conditions.py' - 'src/main/resources/aws/rest-routes.json' - 'tools/aws/regen_rest_routes.py' - 'tools/aws/test_regen_rest_routes.py' diff --git a/Makefile b/Makefile index 718b5b1ad2..d9b4689620 100644 --- a/Makefile +++ b/Makefile @@ -647,7 +647,9 @@ REQUEST_CONDITION_KEYS_PATHS := src/main/resources/aws/request-condition-keys.js tools/aws/regen_dynamodb_condition_keys.py tools/aws/regen_iam_tag_on_create.py $(IAM_PASSED_ROLES_GENERATOR) \ tools/aws/sources/eventbridge-condition-keys.json tools/aws/fetch_eventbridge_conditions.py \ tools/aws/test_fetch_eventbridge_conditions.py tools/aws/sources/eks-condition-keys.json \ - tools/aws/fetch_eks_conditions.py tools/aws/test_fetch_eks_conditions.py + tools/aws/fetch_eks_conditions.py tools/aws/test_fetch_eks_conditions.py \ + tools/aws/sources/route53-condition-keys.json tools/aws/fetch_route53_conditions.py \ + tools/aws/test_fetch_route53_conditions.py DOCUMENTED_ROUTES_PATHS := src/main/resources/aws/rest-routes.json tools/aws/regen_rest_routes.py \ tools/aws/test_regen_rest_routes.py tools/aws/regen_partitions.py tools/aws/regen_query_services.py IAM_REQUEST_RESOURCES_PATHS := src/main/resources/aws/iam-request-resources.json \ diff --git a/docs/services/iam.md b/docs/services/iam.md index 5fce55b657..61f8129ff0 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -4173,6 +4173,19 @@ floci populates: `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. +- `route53:VPCs`: the VPC an `AssociateVPCWithHostedZone`, `DisassociateVPCFromHostedZone`, `CreateHostedZone`, + `CreateVPCAssociationAuthorization` or `DeleteVPCAssociationAuthorization` request names in its body, or a + `ListHostedZonesByVPC` request in its `vpcid` and `vpcregion` query parameters, as + `VPCId=,VPCRegion=`, the values as the request gives them. A request naming no VPC, as a public + `CreateHostedZone` does, carries none. Route 53 reads the VPC only where its schema puts it, the `VPC` below the + request's root, and refuses a second `VPC`, a second `VPCId` or `VPCRegion`, or a repeated `vpcid` or `vpcregion` + query parameter with `InvalidInput`, as it refuses a change batch naming an element twice, so the VPC IAM checks is + the one the request acts on. + Neither botocore nor the Service Reference says where a request carries the key or in what form, so a vendored + source, `tools/aws/sources/route53-condition-keys.json`, written by `tools/aws/fetch_route53_conditions.py` from the + [Route 53 condition keys](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/specifying-conditions-route53.html) + page, gives the operations and the format: "a list of VPCs in the request of" those six, "in the format of + VPCId=,VPCRegion=". The page asks for the values in lowercase, as AWS's VPC ids and Regions are. - `events:source`, `events:detail-type`, `events:detail.service`, `events:detail.eventTypeCode` and `events:detail.userIdentity.principalId`: each literal string a `PutRule` request's event pattern gives the event's field of that name, and `events:TargetArn`: the `Arn` of each target a `PutTargets` request adds, not its 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 4e26254196..ea8c8ee6e7 100644 --- a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java @@ -50,6 +50,8 @@ import java.util.Optional; import java.util.Set; import java.util.TreeMap; import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * Builds the IAM request context: the condition keys a policy's Condition block can match, @@ -73,6 +75,8 @@ public class IamConditionContextResolver { private static final ObjectMapper RESOURCE_MAPPER = new ObjectMapper().findAndRegisterModules(); /** Reads the JSON document a request member holds as a string (an EventBridge rule's event pattern). */ private static final ObjectMapper DOCUMENT_MAPPER = new ObjectMapper(); + /** A member's place in a format of members the request condition key table gives ({@code {VPC.VPCId}}). */ + private static final Pattern MEMBER_PLACE = Pattern.compile("\\{([^}]+)}"); /** Set by {@code ResourceArnBuilder.readJsonBody}, which runs earlier in the same filter pass. */ static final String BUFFERED_JSON_BODY = "floci.bufferedJsonBody"; @@ -468,29 +472,72 @@ public class IamConditionContextResolver { } String namespace = action.substring(0, action.indexOf(':')); String protocol = RequestConditionKeys.protocol(namespace); - Function> values; + List bodyMembers = keys.stream().flatMap(key -> RequestConditionKeys.members(action, key).stream()) + .flatMap(member -> placedMembers(member).stream()).filter(member -> !member.startsWith("?")).toList(); + Function> body; if ("query".equals(protocol) || "ec2".equals(protocol)) { Map form = formParameters(ctx); - values = member -> form.containsKey(member) ? List.of(form.get(member)) : List.of(); + body = 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); + Map> read = bodyMembers.isEmpty() ? Map.of() + : XmlParser.valuesAt(bodyText(ctx), bodyMembers); 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()); + body = member -> read.getOrDefault(member, List.of()); } else if ("json".equals(protocol) || "rest-json".equals(protocol)) { - JsonNode body = PassedRoles.jsonBody(ctx); - if (body == null) { + JsonNode json = bodyMembers.isEmpty() ? null : PassedRoles.jsonBody(ctx); + if (json == null && !bodyMembers.isEmpty()) { return null; } - values = member -> memberValues(body, member); + body = member -> json == null ? List.of() : memberValues(json, member); } else { return null; } - return requestConditions(action, values, requestConditionSpelling(namespace)); + MultivaluedMap query = ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters(); + Function> values = member -> member.startsWith("?") + ? (query == null ? List.of() : query.getOrDefault(member.substring(1), List.of())) + : body.apply(member); + return requestConditions(action, member -> formattedValues(member, values), + requestConditionSpelling(namespace)); + } + + /** + * The members a member of the table names: itself, or, for a format of members (Route 53's + * {@code VPCId={VPC.VPCId},VPCRegion={VPC.VPCRegion}}), each member in braces in it. + */ + private static List placedMembers(String member) { + if (member.indexOf('{') < 0) { + return List.of(member); + } + List placed = new ArrayList<>(); + Matcher place = MEMBER_PLACE.matcher(member); + while (place.find()) { + placed.add(place.group(1)); + } + return placed; + } + + /** + * The values of a member of the table as {@code values} reads each member: its own, or, for a format of members, + * the format with each member's place holding its value, when each holds one; none when one holds none or several. + */ + private static List formattedValues(String member, Function> values) { + if (member.indexOf('{') < 0) { + return values.apply(member); + } + StringBuilder formatted = new StringBuilder(); + Matcher place = MEMBER_PLACE.matcher(member); + while (place.find()) { + List value = values.apply(place.group(1)); + if (value.size() != 1) { + return List.of(); + } + place.appendReplacement(formatted, Matcher.quoteReplacement(value.getFirst())); + } + place.appendTail(formatted); + return List.of(formatted.toString()); } /** 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 5e85aafec9..8af890f67b 100644 --- a/src/main/java/io/floci/aws/services/route53/Route53Controller.java +++ b/src/main/java/io/floci/aws/services/route53/Route53Controller.java @@ -22,7 +22,9 @@ import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriInfo; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamReader; @@ -407,8 +409,15 @@ public class Route53Controller { public Response listHostedZonesByVpc(@QueryParam("vpcid") String vpcId, @QueryParam("vpcregion") String vpcRegion, @QueryParam("maxitems") @DefaultValue("100") int maxItems, - @QueryParam("nexttoken") String nextToken) { + @QueryParam("nexttoken") String nextToken, + @Context UriInfo uriInfo) { try { + // One VPC, as IAM reads route53:VPCs from these same parameters: a second copy of either is refused. + for (String parameter : List.of("vpcid", "vpcregion")) { + if (uriInfo != null && uriInfo.getQueryParameters().getOrDefault(parameter, List.of()).size() > 1) { + throw new AwsException("InvalidInput", "The request names " + parameter + " more than once.", 400); + } + } if (vpcId == null || vpcId.isEmpty()) { throw new AwsException("InvalidInput", "VPCId is required.", 400); } @@ -936,14 +945,60 @@ public class Route53Controller { // ── Request parsers ─────────────────────────────────────────────────────── + /** + * The VPC a request names, read only where Route 53's schema puts it, its {@code VPCId} and {@code VPCRegion} in + * the {@code VPC} below the request's root, refusing a second {@code VPC} or a second copy of either, as a change + * batch's elements are refused. IAM reads {@code route53:VPCs} from these same elements, through the members the + * generated condition key table names, so both read one VPC. Null when the request names none. + */ private VpcAssociation parseVpcAssociation(String body) { - List> vpcs = XmlParser.extractGroups(body, "VPC"); - if (vpcs.isEmpty()) { + if (body == null || body.isBlank()) { + return null; + } + boolean named = false; + String vpcId = null; + String vpcRegion = null; + try { + XMLStreamReader r = XmlParser.newStreamReader(body); + Deque open = new ArrayDeque<>(); + boolean rootOpen = false; + Set read = new HashSet<>(); + while (r.hasNext()) { + int event = r.next(); + if (event == XMLStreamConstants.START_ELEMENT) { + if (!rootOpen) { + rootOpen = true; + continue; + } + String name = r.getLocalName(); + if (open.isEmpty() && "VPC".equals(name)) { + readOnce(read, name); + named = true; + } else if (open.size() == 1 && "VPC".equals(open.peekLast()) + && ("VPCId".equals(name) || "VPCRegion".equals(name))) { + readOnce(read, name); + String text = r.getElementText(); + if ("VPCId".equals(name)) { + vpcId = text; + } else { + vpcRegion = text; + } + continue; + } + open.addLast(name); + } else if (event == XMLStreamConstants.END_ELEMENT && !open.isEmpty()) { + open.pollLast(); + } + } + r.close(); + } catch (AwsException e) { + throw e; + } catch (Exception e) { + throw new AwsException("InvalidInput", "The XML you provided was not well-formed.", 400); + } + if (!named) { return null; } - Map vpc = vpcs.get(0); - String vpcId = vpc.get("VPCId"); - String vpcRegion = vpc.get("VPCRegion"); // AWS requires VPCId and VPCRegion together whenever VPC is present; a // half-populated element must not mark the zone private. if (vpcId == null || vpcId.isEmpty() || vpcRegion == null || vpcRegion.isEmpty()) { diff --git a/src/main/resources/aws/request-condition-keys.json b/src/main/resources/aws/request-condition-keys.json index 851142d4c3..679bc441eb 100644 --- a/src/main/resources/aws/request-condition-keys.json +++ b/src/main/resources/aws/request-condition-keys.json @@ -83,11 +83,29 @@ "redshift:GetClusterCredentials": [ "redshift:DbUser" ], + "route53:AssociateVPCWithHostedZone": [ + "route53:VPCs" + ], "route53:ChangeResourceRecordSets": [ "route53:ChangeResourceRecordSetsActions", "route53:ChangeResourceRecordSetsNormalizedRecordNames", "route53:ChangeResourceRecordSetsRecordTypes" ], + "route53:CreateHostedZone": [ + "route53:VPCs" + ], + "route53:CreateVPCAssociationAuthorization": [ + "route53:VPCs" + ], + "route53:DeleteVPCAssociationAuthorization": [ + "route53:VPCs" + ], + "route53:DisassociateVPCFromHostedZone": [ + "route53:VPCs" + ], + "route53:ListHostedZonesByVPC": [ + "route53:VPCs" + ], "sts:AssumeRole": [ "sts:ExternalId", "sts:RoleSessionName" @@ -200,6 +218,11 @@ "DbUser" ] }, + "route53:AssociateVPCWithHostedZone": { + "route53:VPCs": [ + "VPCId={VPC.VPCId},VPCRegion={VPC.VPCRegion}" + ] + }, "route53:ChangeResourceRecordSets": { "route53:ChangeResourceRecordSetsActions": [ "ChangeBatch.Changes.Change.Action" @@ -211,6 +234,31 @@ "ChangeBatch.Changes.Change.ResourceRecordSet.Type" ] }, + "route53:CreateHostedZone": { + "route53:VPCs": [ + "VPCId={VPC.VPCId},VPCRegion={VPC.VPCRegion}" + ] + }, + "route53:CreateVPCAssociationAuthorization": { + "route53:VPCs": [ + "VPCId={VPC.VPCId},VPCRegion={VPC.VPCRegion}" + ] + }, + "route53:DeleteVPCAssociationAuthorization": { + "route53:VPCs": [ + "VPCId={VPC.VPCId},VPCRegion={VPC.VPCRegion}" + ] + }, + "route53:DisassociateVPCFromHostedZone": { + "route53:VPCs": [ + "VPCId={VPC.VPCId},VPCRegion={VPC.VPCRegion}" + ] + }, + "route53:ListHostedZonesByVPC": { + "route53:VPCs": [ + "VPCId={?vpcid},VPCRegion={?vpcregion}" + ] + }, "sts:AssumeRole": { "sts:ExternalId": [ "ExternalId" diff --git a/src/test/java/io/floci/aws/core/common/Route53VpcConditionsIntegrationTest.java b/src/test/java/io/floci/aws/core/common/Route53VpcConditionsIntegrationTest.java new file mode 100644 index 0000000000..f68b700e10 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/Route53VpcConditionsIntegrationTest.java @@ -0,0 +1,150 @@ +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.ec2.Ec2Client; +import software.amazon.awssdk.services.route53.Route53Client; +import software.amazon.awssdk.services.route53.model.Route53Exception; +import software.amazon.awssdk.services.route53.model.VPCRegion; + +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.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * A Route 53 VPC association call is checked with {@code route53:VPCs}, the VPC its request names in the format + * Route 53's developer guide gives, {@code VPCId=,VPCRegion=}: in the body of + * AssociateVPCWithHostedZone, DisassociateVPCFromHostedZone and CreateHostedZone, and in the query string of + * ListHostedZonesByVPC. A request naming no VPC carries no value. + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class Route53VpcConditionsIntegrationTest { + + private static final String ACCOUNT = "000000000000"; + + @TestHTTPResource("/") + URI endpoint; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void aVpcAssociationCallIsCheckedWithTheVpcItsRequestNames() { + String user = "vpc-conditions-" + UUID.randomUUID(); + UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), auth(ACCOUNT, "iam"), + user); + try (Route53Client client = AwsTestClients.create(Route53Client.builder(), credentials.accessKeyId(), + credentials.secretAccessKey(), Region.US_EAST_1, endpoint); + Route53Client admin = AwsTestClients.create(Route53Client.builder(), ACCOUNT, Region.US_EAST_1, endpoint); + Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), ACCOUNT, Region.US_EAST_1, endpoint)) { + String home = ec2.createVpc(r -> r.cidrBlock("10.91.0.0/16")).vpc().vpcId(); + String allowed = ec2.createVpc(r -> r.cidrBlock("10.92.0.0/16")).vpc().vpcId(); + String other = ec2.createVpc(r -> r.cidrBlock("10.93.0.0/16")).vpc().vpcId(); + String zone = admin.createHostedZone(r -> r.name("vpcs.internal") + .callerReference(UUID.randomUUID().toString()) + .vpc(v -> v.vpcId(home).vpcRegion(VPCRegion.US_EAST_1))).hostedZone().id(); + + policy(user, onVpc("Allow", "route53:AssociateVPCWithHostedZone", "StringEquals", allowed)); + denied(() -> client.associateVPCWithHostedZone(r -> r.hostedZoneId(zone) + .vpc(v -> v.vpcId(other).vpcRegion(VPCRegion.US_EAST_1)))); + client.associateVPCWithHostedZone(r -> r.hostedZoneId(zone) + .vpc(v -> v.vpcId(allowed).vpcRegion(VPCRegion.US_EAST_1))); + + // ListHostedZonesByVPC names its VPC in its query string. + policy(user, onVpc("Allow", "route53:ListHostedZonesByVPC", "StringEquals", allowed)); + client.listHostedZonesByVPC(r -> r.vpcId(allowed).vpcRegion(VPCRegion.US_EAST_1)); + denied(() -> client.listHostedZonesByVPC(r -> r.vpcId(other).vpcRegion(VPCRegion.US_EAST_1))); + + // An explicit deny on a VPC holds against an allow of every association. + policy(user, "{\"Effect\":\"Allow\",\"Action\":\"route53:DisassociateVPCFromHostedZone\"," + + "\"Resource\":\"*\"}," + onVpc("Deny", "route53:DisassociateVPCFromHostedZone", "StringEquals", + allowed)); + denied(() -> client.disassociateVPCFromHostedZone(r -> r.hostedZoneId(zone) + .vpc(v -> v.vpcId(allowed).vpcRegion(VPCRegion.US_EAST_1)))); + + // A public zone names no VPC, so a grant conditioned on one does not cover it. + policy(user, onVpc("Allow", "route53:CreateHostedZone", "StringEquals", allowed)); + denied(() -> client.createHostedZone(r -> r.name("public.vpcs.test").callerReference(UUID.randomUUID() + .toString()))); + client.createHostedZone(r -> r.name("private.vpcs.internal").callerReference(UUID.randomUUID().toString()) + .vpc(v -> v.vpcId(allowed).vpcRegion(VPCRegion.US_EAST_1))); + } + } + + /** + * A request naming a second VPC, or a VPC's id or Region twice, is refused before it acts, as a change batch + * naming an element twice is: IAM reads one VPC from the elements the handler reads, so a Deny on a VPC cannot be + * passed by naming it beside another. + */ + @Test + void aRequestNamingTheVpcTwiceIsRefusedBeforeItActs() { + String user = "vpc-twice-" + UUID.randomUUID(); + UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), auth(ACCOUNT, "iam"), + user); + try (Route53Client admin = AwsTestClients.create(Route53Client.builder(), ACCOUNT, Region.US_EAST_1, endpoint); + Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), ACCOUNT, Region.US_EAST_1, endpoint)) { + String home = ec2.createVpc(r -> r.cidrBlock("10.94.0.0/16")).vpc().vpcId(); + String forbidden = ec2.createVpc(r -> r.cidrBlock("10.95.0.0/16")).vpc().vpcId(); + String other = ec2.createVpc(r -> r.cidrBlock("10.96.0.0/16")).vpc().vpcId(); + String zone = admin.createHostedZone(r -> r.name("twice.internal") + .callerReference(UUID.randomUUID().toString()) + .vpc(v -> v.vpcId(home).vpcRegion(VPCRegion.US_EAST_1))).hostedZone().id(); + policy(user, "{\"Effect\":\"Allow\",\"Action\":\"route53:*\",\"Resource\":\"*\"}," + + onVpc("Deny", "route53:AssociateVPCWithHostedZone", "StringEquals", forbidden) + "," + + onVpc("Deny", "route53:ListHostedZonesByVPC", "StringEquals", forbidden)); + String path = "/2013-04-01/hostedzone/" + zone.replace("/hostedzone/", "") + "/associatevpc"; + String twoIds = "" + forbidden + "" + other + "" + + "us-east-1"; + for (String vpcs : new String[] {vpc(forbidden) + vpc(other), twoIds}) { + given().port(endpoint.getPort()).header("Authorization", auth(credentials.accessKeyId(), "route53")) + .contentType("application/xml") + .body("" + vpcs + + "") + .post(path).then().statusCode(400).body(containsString("InvalidInput")); + } + assertEquals(List.of(home), admin.getHostedZone(r -> r.id(zone)).vpCs().stream().map(v -> v.vpcId()) + .toList()); + given().port(endpoint.getPort()).header("Authorization", auth(credentials.accessKeyId(), "route53")) + .get("/2013-04-01/hostedzonesbyvpc?vpcid=" + forbidden + "&vpcid=" + other + + "&vpcregion=us-east-1") + .then().statusCode(400).body(containsString("InvalidInput")); + } + } + + private static String vpc(String id) { + return "" + id + "us-east-1"; + } + + /** A statement of the effect on the action, conditioned on {@code route53:VPCs} being the VPC in us-east-1. */ + private static String onVpc(String effect, String action, String operator, String vpc) { + return "{\"Effect\":\"" + effect + "\",\"Action\":\"" + action + "\",\"Resource\":\"*\",\"Condition\":{\"" + + operator + "\":{\"route53:VPCs\":\"VPCId=" + vpc + ",VPCRegion=us-east-1\"}}}"; + } + + private static void denied(Runnable call) { + Route53Exception error = assertThrows(Route53Exception.class, call::run); + assertEquals(403, error.statusCode()); + } + + private void policy(String user, String statements) { + EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth(ACCOUNT, "iam"), user, "vpcs", + "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}"); + } +} diff --git a/tools/aws/fetch_route53_conditions.py b/tools/aws/fetch_route53_conditions.py new file mode 100644 index 0000000000..0cb32e6c95 --- /dev/null +++ b/tools/aws/fetch_route53_conditions.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python3 +"""Vendor which request members a Route 53 condition key composes into tools/aws/sources/route53-condition-keys.json, +a source of the request condition key table. + +AWS's Service Reference gives AssociateVPCWithHostedZone, DisassociateVPCFromHostedZone, ListHostedZonesByVPC, +CreateHostedZone, CreateVPCAssociationAuthorization and DeleteVPCAssociationAuthorization the key `route53:VPCs` +without saying where a request carries it, or in what form, and botocore does not say it either. Route 53's developer +guide does, in its table of the condition keys Route 53 defines: + + route53:VPCs AssociateVPCWithHostedZone DisassociateVPCFromHostedZone ListHostedZonesByVPC CreateHostedZone + CreateVPCAssociationAuthorization DeleteVPCAssociationAuthorization Multi-valued + Represents a list of VPCs in the request of AssociateVPCWithHostedZone, ..., in the format of + "VPCId=,VPCRegion= + + https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/specifying-conditions-route53.html + +This script copies the row of each key the table gives in a format of request members, `=` pairs, as +it stands, with the operations it names and the members of its format, in order. A row giving no such format is not +read here. Nothing in the output is written by hand; regen_request_condition_keys.py reads it to give the table each +key as its format composes those members of each operation's request. + +Run from anywhere in the repo: + python3 tools/aws/fetch_route53_conditions.py # rewrite the vendored file from the page + python3 tools/aws/fetch_route53_conditions.py --verify # online: the file still says what the page does +""" +from __future__ import annotations + +import argparse +import html +import json +import re +import sys +import urllib.request +from datetime import datetime, timezone +from pathlib import Path + +PAGE = "https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/specifying-conditions-route53.html" +REPO_ROOT = Path(__file__).resolve().parents[2] +OUTPUT = REPO_ROOT / "tools/aws/sources/route53-condition-keys.json" + +# The header of the page's table of condition keys. +HEADER = ["Route 53 Condition Key", "API operations", "Value type", "Description"] +# A description giving the key's value in a format of request members. +FORMAT_RE = re.compile(r'\bin the format of "?(?P[A-Za-z]+=<[a-z-]+>(?:,[A-Za-z]+=<[a-z-]+>)+)') +MEMBER_RE = re.compile(r"(?P[A-Za-z]+)=<[a-z-]+>") +KEY_RE = re.compile(r"^route53:[A-Za-z]+$") +OPERATION_RE = re.compile(r"^[A-Z][A-Za-z]+$") + + +def text(fragment: str) -> str: + """A fragment of a page as text, spaces collapsed.""" + return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment))).strip() + + +def body(page: str) -> str: + """The page's own content, its navigation left out.""" + match = re.search(r'
(?P.*?)(?:
list[list[str]]: + """The rows of the page's table of condition keys, each its key, operations, value type and description.""" + for table in re.findall(r"]*>(.*?)", body(page), re.S): + rows = [[text(cell) for cell in re.findall(r"]*>(.*?)", row, re.S)] + for row in re.findall(r"(.*?)", table, re.S)] + if rows and rows[0] == HEADER: + return [row for row in rows[1:] if len(row) == len(HEADER) and KEY_RE.match(row[0])] + raise ValueError(f"{PAGE} has no table of Route 53 condition keys: its layout changed") + + +def build(fetch) -> dict: + keys = [] + for key, operations, value_type, description in key_rows(fetch(PAGE)): + found = FORMAT_RE.search(description) + if found is None: + continue + named = operations.split() + if not named or not all(OPERATION_RE.match(name) for name in named): + raise ValueError(f"{PAGE} names {key}'s operations as '{operations}': its layout changed") + keys.append({"key": key, "operations": named, "format": found.group("format"), + "members": MEMBER_RE.findall(found.group("format")), "valueType": value_type, + "row": description}) + if not keys: + raise ValueError(f"{PAGE} gives no key in a format of request members: its layout changed") + return { + "_source": { + "page": PAGE, + "fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)), + "retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"), + "note": "Each Route 53 key whose row of the page's table of condition keys gives its value in a format of " + "request members, with the operations the row names, the format and its members in order, and " + "the row's description, copied as it stands.", + }, + "keys": sorted(keys, key=lambda entry: entry["key"]), + } + + +def fetch_url(url: str) -> str: + request = urllib.request.Request(url, headers={"User-Agent": "floci-tools"}) + with urllib.request.urlopen(request, timeout=60) as response: + return response.read().decode("utf-8") + + +def stale(vendored: dict, page: str) -> bool: + """Whether the page now gives something other than the vendored file, its date aside.""" + return vendored.get("keys") != build(lambda url: page)["keys"] + + +def main(argv: list[str] | None = None, fetch=fetch_url) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--verify", action="store_true", help="online: the vendored file matches the page") + args = parser.parse_args(argv) + try: + page = fetch(PAGE) + except OSError as e: + print(f"error: could not read the Route 53 developer guide ({e})", file=sys.stderr) + return 2 + if args.verify: + vendored = json.loads(OUTPUT.read_text(encoding="utf-8")) + if stale(vendored, page): + print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the Route 53 developer guide does: run " + f"tools/aws/fetch_route53_conditions.py and then make request-condition-keys-sync", file=sys.stderr) + return 1 + print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the Route 53 developer guide") + return 0 + built = build(lambda url: page) + OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8") + print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['keys'])} keys)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/aws/regen_request_condition_keys.py b/tools/aws/regen_request_condition_keys.py index c9a327a1f7..275eb25975 100644 --- a/tools/aws/regen_request_condition_keys.py +++ b/tools/aws/regen_request_condition_keys.py @@ -25,7 +25,9 @@ it. `SERVICES` names, for each namespace, the keys read and where: - `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 service registers for that shape. The six VPC association operations are checked with the VPC they name as + `route53:VPCs`, `VPCId=,VPCRegion=`, as the developer guide gives it (`CONDITION_SOURCES`), read + from the body or, for ListHostedZonesByVPC, the query string. - `events`: a PutRule request is checked with the literal strings its event pattern gives the event's `source`, `detail-type`, `detail.service`, `detail.eventTypeCode` and `detail.userIdentity.principalId` fields as `events:source`, `events:detail-type` and the `events:detail.*` keys, and a PutTargets request with the ARN of @@ -77,12 +79,14 @@ from __future__ import annotations import argparse import json +import re import sys import urllib.request from pathlib import Path import fetch_eks_conditions import fetch_eventbridge_conditions +import fetch_route53_conditions from regen_dynamodb_condition_keys import member_paths from regen_iam_tag_on_create import _condition_keys, _resource_keys from regen_partitions import resolve_botocore_data @@ -92,6 +96,9 @@ REPO_ROOT = Path(__file__).resolve().parents[2] OUTPUT = REPO_ROOT / "src/main/resources/aws/request-condition-keys.json" REFERENCE = "https://servicereference.us-east-1.amazonaws.com/" FLAT_PROTOCOLS = ("query", "ec2") +# A `=` part of a key's format, and a member's place in the format the table writes. +FORMAT_VALUE_RE = re.compile(r"(?P[A-Za-z]+)=<[a-z-]+>") +FORMAT_PLACE_RE = re.compile(r"\{(?P[A-Za-z]+)}") # For each namespace: its botocore model, each key read from the request with the name of the member that # carries it, each key read from the stored resource, and the actions that take a key their request does not @@ -162,38 +169,49 @@ SERVICES = { # `eks:kubernetesGroups`, `eks:policyArn` and `eks:namespaces` as "the present in the access entry requests" # or in "the associate / disassociate access policy requests", and `eks:accessEntryType` and `eks:username` as "the # access entry type" and "the Kubernetes username" present in them; tools/aws/fetch_eks_conditions.py vendors that -# page and `vendored_service` reads it. Each file is written by its own script from the page, unchanged, and nothing -# about an operation is stated here. +# page and `vendored_service` reads it. And granted for Route 53: its developer guide's table of condition keys gives +# `route53:VPCs` as "a list of VPCs in the request of" the six VPC association operations, "in the format of +# VPCId=,VPCRegion="; tools/aws/fetch_route53_conditions.py vendors that page and `vendored_service` +# reads it. Each file is written by its own script from the page, unchanged, and nothing about an operation is stated +# here. CONDITION_SOURCES: dict[str, dict] = { "eks": {"model": "eks", "source": REPO_ROOT / "tools/aws/sources/eks-condition-keys.json", "fetcher": fetch_eks_conditions}, "events": {"model": "events", "source": REPO_ROOT / "tools/aws/sources/eventbridge-condition-keys.json", "fetcher": fetch_eventbridge_conditions}, + "route53": {"model": "route53", "source": REPO_ROOT / "tools/aws/sources/route53-condition-keys.json", + "fetcher": fetch_route53_conditions}, } def vendored_service(namespace: str) -> dict: """The `SERVICES` entry of a namespace a vendored page gives (`CONDITION_SOURCES`), beside any it has: each key - read from the member the page says carries it, a field of a JSON document after `#`, in the one operation the - page names for it where it names one (`operations`). The page gives what a request carries, so a key is read - from an action's request only where the reference lists it on that action, not only on a resource type, whose - key is the stored resource's value (`vendored`).""" + read from the member the page says carries it, a field of a JSON document after `#`, or the members its format + composes, each in braces in the format's place of its value (`VPCId={VPCId},VPCRegion={VPCRegion}`), in the + operations the page names for it where it names them (`operations`). The page gives what a request carries, so a + key is read from an action's request only where the reference lists it on that action, not only on a resource + type, whose key is the stored resource's value (`vendored`).""" granted = CONDITION_SOURCES[namespace] document = json.loads(granted["source"].read_text(encoding="utf-8")) base = SERVICES.get(namespace, {"request": {}, "stored": (), "not_in_request": {}}) request, operations = dict(base["request"]), {} for entry in document["keys"]: - request[entry["key"]] = entry["member"] + (f"#{entry['field']}.*" if "field" in entry else "") - if "operation" in entry: - operations[entry["key"]] = entry["operation"] + if "format" in entry: + request[entry["key"]] = FORMAT_VALUE_RE.sub( + lambda part: f"{part.group('member')}={{{part.group('member')}}}", entry["format"]) + else: + request[entry["key"]] = entry["member"] + (f"#{entry['field']}.*" if "field" in entry else "") + if "operation" in entry or "operations" in entry: + operations[entry["key"]] = frozenset(entry.get("operations") or [entry["operation"]]) return {**base, "model": granted["model"], "request": request, "operations": operations, "vendored": frozenset(entry["key"] for entry in document["keys"])} SERVICES.update({namespace: vendored_service(namespace) for namespace in CONDITION_SOURCES}) -# The locations a request carries a member outside its body in, which the request condition reader does not read. -OUTSIDE_THE_BODY = {"uri", "querystring", "header", "headers"} +# The locations a request carries a member outside its body and query string in, which the request condition reader +# does not read. +OUTSIDE_THE_BODY = {"uri", "header", "headers"} def url(namespace: str) -> str: @@ -246,8 +264,11 @@ def _located(namespace: str, model: dict | None, actions: dict[str, list[str]]): for key in keys: if key not in service["request"] or (action, key) in service["not_in_request"]: continue - # A vendored page names the one operation it reads a key from; another taking the key is not read. - if service.get("operations", {}).get(key, action.split(":", 1)[1]) != action.split(":", 1)[1]: + # A vendored page names the operations it reads a key from; another taking the key is not read. + if action.split(":", 1)[1] not in service.get("operations", {}).get(key, {action.split(":", 1)[1]}): + continue + if "{" in service["request"][key]: + yield from _formatted(action, key, service["request"][key], model, protocol) continue name, _, document = service["request"][key].partition("#") if model is None: # not modelled by botocore: the member is the name SERVICES gives @@ -284,6 +305,23 @@ def _located(namespace: str, model: dict | None, actions: dict[str, list[str]]): yield action, key, carried + (f"#{document}" if document else ""), shape +def _formatted(action: str, key: str, template: str, model: dict, protocol: str): + """The (action, key, path, shape) of a key a vendored page gives as a format of request members: the format with + each member's place holding the path the request carries it at, in braces (`VPCId={VPC.VPCId}`), and no shape. Each + member must be one member of the request.""" + operation = model["operations"].get(action.split(":", 1)[1]) + if operation is None or "input" not in operation: + raise ValueError(f"{action} takes {key} but botocore has no request for it") + + def carried(found: re.Match) -> str: + paths = member_paths(model, operation["input"]["shape"], {found.group("member")}) + if len(paths) != 1: + raise ValueError(f"{action} takes {key} from {found.group('member')}, which its request has " + f"{len(paths)} of, not one") + return "{" + carried_member(model, operation["input"]["shape"], paths[0], protocol == "rest-xml")[0] + "}" + yield action, key, FORMAT_PLACE_RE.sub(carried, template), None + + def _in_the_body(model: dict, shape: str, path: str) -> bool: """Whether the request carries the member at `path` in its body, not in its URI, query string or headers.""" return model["shapes"][shape]["members"][path.split(".", 1)[0]].get("location") not in OUTSIDE_THE_BODY @@ -303,8 +341,12 @@ def _scalar_or_list(model: dict, shape: str, path: str) -> bool: 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.""" + member. A member of the query string is `?` and the parameter's name (`?vpcid`), read from the query of a request + of any protocol. 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.""" + first = model["shapes"][shape]["members"].get(path.split(".", 1)[0], {}) + if first.get("location") == "querystring" and "." not in path: + return "?" + first.get("locationName", path), first["shape"] steps = [] for index, step in enumerate(path.split(".")): spec = model["shapes"][shape] diff --git a/tools/aws/sources/route53-condition-keys.json b/tools/aws/sources/route53-condition-keys.json new file mode 100644 index 0000000000..5277aed904 --- /dev/null +++ b/tools/aws/sources/route53-condition-keys.json @@ -0,0 +1,28 @@ +{ + "_source": { + "page": "https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/specifying-conditions-route53.html", + "fetcher": "tools/aws/fetch_route53_conditions.py", + "retrieved": "2026-11-28", + "note": "Each Route 53 key whose row of the page's table of condition keys gives its value in a format of request members, with the operations the row names, the format and its members in order, and the row's description, copied as it stands." + }, + "keys": [ + { + "key": "route53:VPCs", + "operations": [ + "AssociateVPCWithHostedZone", + "DisassociateVPCFromHostedZone", + "ListHostedZonesByVPC", + "CreateHostedZone", + "CreateVPCAssociationAuthorization", + "DeleteVPCAssociationAuthorization" + ], + "format": "VPCId=,VPCRegion=", + "members": [ + "VPCId", + "VPCRegion" + ], + "valueType": "Multi-valued", + "row": "Represents a list of VPCs in the request of AssociateVPCWithHostedZone , DisassociateVPCFromHostedZone , ListHostedZonesByVPC , CreateHostedZone , CreateVPCAssociationAuthorization , and DeleteVPCAssociationAuthorization , in the format of \"VPCId=,VPCRegion=" + } + ] +} diff --git a/tools/aws/test_fetch_route53_conditions.py b/tools/aws/test_fetch_route53_conditions.py new file mode 100644 index 0000000000..a4c9fa7fc4 --- /dev/null +++ b/tools/aws/test_fetch_route53_conditions.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +"""Tests for fetch_route53_conditions.py, on a page in the Route 53 developer guide's markup.""" +from __future__ import annotations + +import pytest + +import fetch_route53_conditions as f + +HEADER = "Route 53 Condition KeyAPI operationsValue typeDescription" + + +def row(key: str, operations: str, description: str) -> str: + return (f"

{key}

{operations}

Multi-valued

" + f"

{description}

") + + +VPCS = row("route53:VPCs", "

AssociateVPCWithHostedZone

ListHostedZonesByVPC

", + 'Represents a list of VPCs in the request of AssociateVPCWithHostedZone and ListHostedZonesByVPC, in the ' + 'format of "VPCId=<vpc-id>,VPCRegion=<region>') +ACTIONS = row("route53:ChangeResourceRecordSetsActions", "ChangeResourceRecordSets", + "Represents a list of actions in the request of ChangeResourceRecordSets.") + + +def page(rows: str = VPCS + ACTIONS) -> str: + return f'
{HEADER}{rows}
' + + +def test_a_key_in_a_format_of_members_is_read_with_its_operations_and_members(): + keys = {entry["key"]: entry for entry in f.build(lambda url: page())["keys"]} + assert keys["route53:VPCs"]["operations"] == ["AssociateVPCWithHostedZone", "ListHostedZonesByVPC"] + assert keys["route53:VPCs"]["format"] == "VPCId=,VPCRegion=" + assert keys["route53:VPCs"]["members"] == ["VPCId", "VPCRegion"] + # A row giving no format of members is not read here. + assert "route53:ChangeResourceRecordSetsActions" not in keys + + +def test_a_page_whose_layout_changed_is_refused(): + with pytest.raises(ValueError, match="no table"): + f.build(lambda url: '
Key
') + with pytest.raises(ValueError, match="no key in a format"): + f.build(lambda url: page(ACTIONS)) + + +def test_the_file_is_stale_when_the_page_says_something_else(): + vendored = f.build(lambda url: page()) + assert not f.stale(vendored, page()) + assert f.stale(vendored, page(VPCS.replace("VPCRegion=", "Region=") + ACTIONS)) diff --git a/tools/aws/test_regen_request_condition_keys.py b/tools/aws/test_regen_request_condition_keys.py index 8326fffa7a..09222bff33 100644 --- a/tools/aws/test_regen_request_condition_keys.py +++ b/tools/aws/test_regen_request_condition_keys.py @@ -148,6 +148,9 @@ def test_the_vendored_table_covers_its_namespaces(): "tools/aws/sources/eks-condition-keys.json", "tools/aws/fetch_eks_conditions.py", "tools/aws/test_fetch_eks_conditions.py", + "tools/aws/sources/route53-condition-keys.json", + "tools/aws/fetch_route53_conditions.py", + "tools/aws/test_fetch_route53_conditions.py", "tools/aws/regen_iam_passed_roles.py", "tools/aws/regen_partitions.py", "tools/aws/regen_query_services.py", @@ -313,3 +316,33 @@ def test_the_vendored_table_reads_eks_access_entries_and_policies(): "eks:namespaces": ["accessScope.namespaces.*"], "eks:policyArn": ["policyArn"]} assert "eks:DisassociateAccessPolicy" not in document["members"] assert "eks:UpdateAccessEntry" not in document["actions"] + + +ROUTE53 = {"metadata": {"protocol": "rest-xml"}, "operations": { + "AssociateVPCWithHostedZone": {"input": {"shape": "Associate"}}, + "ListHostedZonesByVPC": {"input": {"shape": "ByVpc"}}}, "shapes": { + "Associate": {"type": "structure", "members": {"HostedZoneId": {"shape": "String", "location": "uri"}, + "VPC": {"shape": "VPC"}}}, + "VPC": {"type": "structure", "members": {"VPCRegion": {"shape": "String"}, "VPCId": {"shape": "String"}}}, + "ByVpc": {"type": "structure", "members": { + "VPCId": {"shape": "String", "location": "querystring", "locationName": "vpcid"}, + "VPCRegion": {"shape": "String", "location": "querystring", "locationName": "vpcregion"}}}, + "String": {"type": "string"}}} + + +def test_a_vendored_format_composes_the_members_each_request_carries(): + # Route 53's developer guide gives route53:VPCs "in the format of VPCId=,VPCRegion=": each member's + # place holds where the request carries it, in an XML body or in the query string. + actions = {"route53:AssociateVPCWithHostedZone": ["route53:VPCs"], "route53:ListHostedZonesByVPC": ["route53:VPCs"]} + assert request_members("route53", ROUTE53, actions) == { + "route53:AssociateVPCWithHostedZone": {"route53:VPCs": ["VPCId={VPC.VPCId},VPCRegion={VPC.VPCRegion}"]}, + "route53:ListHostedZonesByVPC": {"route53:VPCs": ["VPCId={?vpcid},VPCRegion={?vpcregion}"]}} + assert member_shapes("route53", ROUTE53, actions) == {} + + +def test_the_vendored_table_reads_route53_vpcs(): + document = json.loads(OUTPUT.read_text()) + assert document["members"]["route53:CreateHostedZone"] == { + "route53:VPCs": ["VPCId={VPC.VPCId},VPCRegion={VPC.VPCRegion}"]} + assert document["members"]["route53:ListHostedZonesByVPC"] == { + "route53:VPCs": ["VPCId={?vpcid},VPCRegion={?vpcregion}"]}