diff --git a/src/main/java/io/floci/aws/services/iam/IamActionRegistry.java b/src/main/java/io/floci/aws/services/iam/IamActionRegistry.java index 0accab3f16..777c09da96 100644 --- a/src/main/java/io/floci/aws/services/iam/IamActionRegistry.java +++ b/src/main/java/io/floci/aws/services/iam/IamActionRegistry.java @@ -710,8 +710,9 @@ public class IamActionRegistry { return rule.action(); } } - Optional operation = restRoutes.operation(credentialScope, method, withoutInternalPrefix(ctx, path), - ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters(), movedUnderPrefix(ctx)); + Optional operation = restRoutes.match(credentialScope, method, withoutInternalPrefix(ctx, path), + ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters(), movedUnderPrefix(ctx), + ctx.getHeaders()).map(IamRestRoutes.Match::operation); if (operation.isPresent()) { String action = IamAuthorizedActions.actionFor(credentialScope, operation.get(), method); if (checkedAsAws(credentialScope, operation.get(), action)) { @@ -759,7 +760,8 @@ public class IamActionRegistry { private static Optional matchedRoute(IamRestRoutes routes, String credentialScope, ContainerRequestContext ctx) { return routes.match(credentialScope, ctx.getMethod().toUpperCase(), withoutInternalPrefix(ctx, routedPath(ctx)), - ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters(), movedUnderPrefix(ctx)); + ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters(), movedUnderPrefix(ctx), + ctx.getHeaders()); } /** @@ -780,8 +782,10 @@ public class IamActionRegistry { return action; } String method = ctx.getMethod().toUpperCase(); - return restRoutes.operation(credentialScope, method, withoutInternalPrefix(ctx, routedPath(ctx)), - ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters(), movedUnderPrefix(ctx)) + return restRoutes.match(credentialScope, method, withoutInternalPrefix(ctx, routedPath(ctx)), + ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters(), movedUnderPrefix(ctx), + ctx.getHeaders()) + .map(IamRestRoutes.Match::operation) .filter(operation -> action.equals(IamAuthorizedActions.actionFor(credentialScope, operation, method))) .map(operation -> credentialScope + ":" + operation) .orElse(action); @@ -796,7 +800,7 @@ public class IamActionRegistry { } return IamRestRoutes.vendored().match(operation.substring(0, separator), ctx.getMethod().toUpperCase(), withoutInternalPrefix(ctx, routedPath(ctx)), ctx.getUriInfo().getQueryParameters(), - movedUnderPrefix(ctx)) + movedUnderPrefix(ctx), ctx.getHeaders()) .filter(match -> match.operation().equals(operation.substring(separator + 1))) .map(IamRestRoutes.Match::located).orElse(Map.of()); } diff --git a/src/main/java/io/floci/aws/services/iam/IamRestRoutes.java b/src/main/java/io/floci/aws/services/iam/IamRestRoutes.java index 95b4c7755d..e376a038cd 100644 --- a/src/main/java/io/floci/aws/services/iam/IamRestRoutes.java +++ b/src/main/java/io/floci/aws/services/iam/IamRestRoutes.java @@ -15,6 +15,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; @@ -71,18 +72,22 @@ final class IamRestRoutes { private static final int REST_OF_PATH = 0; /** - * A matched operation, decoded path labels, generated alternative member locations, and whether the route is a - * documented model's, whose request carries none of the operation's members. + * A matched operation, decoded path labels, generated alternative member locations, whether the route is a + * documented model's, whose request carries none of the operation's members, and the model whose route it is. */ - record Match(String operation, Map labels, Map located, boolean documented) { + record Match(String operation, Map labels, Map located, boolean documented, + String model) { } /** * A route: its operation, its path as a pattern capturing each label in turn, the labels' names, each segment's - * rank, the query it names, the members its alternative locates, and whether its model is a documented one. + * rank, the query it names, the members its alternative locates, whether its model is a documented one, the + * query parameters and headers its operation's request must carry where several operations share the route + * ({@code requires}), whether botocore marks the operation deprecated, and its model. */ private record Route(String operation, Pattern path, Pattern spanning, List labels, int[] ranks, - Map query, Map located, boolean documented) { + Map query, Map located, boolean documented, + Set requiredQuery, Set requiredHeaders, boolean deprecated, String model) { /** The route's pattern: each label taking one segment, or, spanning, the segments its value spans. */ Pattern pattern(boolean spanned) { @@ -99,7 +104,16 @@ final class IamRestRoutes { return false; } } - return true; + return requiredQuery.stream().allMatch(parameter -> parameters != null && parameters.containsKey(parameter)); + } + + /** + * Whether the request carries every header the route's operation requires; with no headers known, a route + * requiring one cannot be told to match. + */ + boolean carries(MultivaluedMap headers) { + return requiredHeaders.isEmpty() || headers != null && requiredHeaders.stream() + .allMatch(header -> headers.keySet().stream().anyMatch(header::equalsIgnoreCase)); } /** The value the path gives each label, decoded as the router decodes a path parameter. */ @@ -116,10 +130,35 @@ final class IamRestRoutes { return Map.copyOf(values); } - /** Whether this route is more specific than the other, as {@link IamRestRoutes} orders them. */ + /** + * Whether this route is more specific than the other, as {@link IamRestRoutes} orders them: by its segments, the + * query it names, then by what its operation's request must carry, a route requiring all the other requires and + * more outranking it, and a current operation before a deprecated one requiring the same. The generator lets a + * route's operations through only when what any two require together is what one of them requires, so of the + * routes a request matches one requires all the others do (UploadPartCopy, over CopyObject and UploadPart). + */ boolean outranks(Route other) { int compared = Arrays.compare(ranks, other.ranks); - return compared != 0 ? compared > 0 : query.size() > other.query.size(); + if (compared != 0) { + return compared > 0; + } + if (query.size() != other.query.size()) { + return query.size() > other.query.size(); + } + Set needs = needs(); + Set otherNeeds = other.needs(); + if (!needs.equals(otherNeeds)) { + return needs.containsAll(otherNeeds) || !otherNeeds.containsAll(needs) && needs.size() > otherNeeds.size(); + } + return !deprecated && other.deprecated; + } + + /** What the route's operation's request must carry: its query parameters, then its headers. */ + private Set needs() { + Set needs = new HashSet<>(); + requiredQuery.forEach(parameter -> needs.add("?" + parameter)); + requiredHeaders.forEach(header -> needs.add(header.toLowerCase(Locale.ROOT) + ":")); + return needs; } } @@ -171,22 +210,32 @@ final class IamRestRoutes { /** As {@link #operation(String, String, String, MultivaluedMap, boolean)}, with the label values. */ Optional match(String scope, String method, String path, MultivaluedMap query, boolean movedUnderPrefix) { + return match(scope, method, path, query, movedUnderPrefix, null); + } + + /** + * As {@link #match(String, String, String, MultivaluedMap, boolean)}, the headers a route's operation requires + * checked against the request's {@code headers}. + */ + Optional match(String scope, String method, String path, MultivaluedMap query, + boolean movedUnderPrefix, MultivaluedMap headers) { String requestPath = IamActionRegistry.withoutTrailingSlash(path); - Optional match = best(scope, method, requestPath, query, false); - return match.isPresent() || !movedUnderPrefix ? match : best(scope, method, requestPath, query, true); + Optional match = best(scope, method, requestPath, query, false, headers); + return match.isPresent() || !movedUnderPrefix ? match : best(scope, method, requestPath, query, true, headers); } private Optional best(String scope, String method, String requestPath, MultivaluedMap query, - boolean spanned) { + boolean spanned, MultivaluedMap headers) { Route best = null; for (Route route : routes.getOrDefault(scope, Map.of()).getOrDefault(method, List.of())) { - if (route.matches(requestPath, query, spanned) && (best == null || route.outranks(best))) { + if (route.matches(requestPath, query, spanned) && route.carries(headers) + && (best == null || route.outranks(best))) { best = route; } } return best == null ? Optional.empty() : Optional.of(new Match(best.operation(), best.labelValues(requestPath, spanned), best.located(), - best.documented())); + best.documented(), best.model())); } /** The modelled denial status, or the existing protocol default when the model declares none. */ @@ -262,9 +311,12 @@ final class IamRestRoutes { throw new IllegalStateException(RESOURCE_NAME + " gives " + model.getKey() + " " + operation.getKey() + " no HTTP method or no request URI"); } + JsonNode requires = operation.getValue().path("requires"); routes.computeIfAbsent(scope, ignored -> new HashMap<>()) .computeIfAbsent(method, ignored -> new ArrayList<>()) - .add(route(operation.getKey(), requestUri, Map.of(), documented)); + .add(route(operation.getKey(), requestUri, Map.of(), documented, names(requires.path("query")), + names(requires.path("headers")), + operation.getValue().path("deprecated").asBoolean(false), model.getKey())); JsonNode alternatives = operation.getValue().path("alternatives"); if (!alternatives.isMissingNode() && !alternatives.isArray()) { throw new IllegalStateException(RESOURCE_NAME + " gives " + operation.getKey() @@ -289,7 +341,8 @@ final class IamRestRoutes { located.put(member.getKey(), source); }); routes.get(scope).computeIfAbsent(alternativeMethod, ignored -> new ArrayList<>()) - .add(route(operation.getKey(), uri, Map.copyOf(located), documented)); + .add(route(operation.getKey(), uri, Map.copyOf(located), documented, Set.of(), Set.of(), + false, model.getKey())); }); }); }); @@ -302,8 +355,17 @@ final class IamRestRoutes { return new IamRestRoutes(Map.copyOf(copied), Map.copyOf(denialStatuses), Set.copyOf(documentedScopes)); } + /** The strings of a JSON array, none when it is missing. */ + private static Set names(JsonNode array) { + Set found = new HashSet<>(); + array.forEach(name -> found.add(name.asText())); + return Set.copyOf(found); + } + /** A route of the operation from its request URI, its path's segments and the query after its {@code ?}. */ - private static Route route(String operation, String requestUri, Map located, boolean documented) { + private static Route route(String operation, String requestUri, Map located, boolean documented, + Set requiredQuery, Set requiredHeaders, boolean deprecated, + String model) { int question = requestUri.indexOf('?'); String path = IamActionRegistry.withoutTrailingSlash(question < 0 ? requestUri : requestUri.substring(0, question)); List segments = path.equals("/") ? List.of() : List.of(path.substring(1).split("/", -1)); @@ -346,6 +408,6 @@ final class IamRestRoutes { } return new Route(operation, Pattern.compile(pattern.isEmpty() ? "/" : pattern.toString()), Pattern.compile(spanning.isEmpty() ? "/" : spanning.toString()), List.copyOf(labels), ranks, - Map.copyOf(query), located, documented); + Map.copyOf(query), located, documented, requiredQuery, requiredHeaders, deprecated, model); } } diff --git a/src/main/resources/aws/rest-routes.json b/src/main/resources/aws/rest-routes.json index 378c17623e..af47424255 100644 --- a/src/main/resources/aws/rest-routes.json +++ b/src/main/resources/aws/rest-routes.json @@ -1970,10 +1970,11 @@ "credentialScope": "s3", "apiVersion": "2006-03-01", "accessDeniedStatus": 403, + "signedElsewhere": {"ListDirectoryBuckets": "s3express", "WriteGetObjectResponse": "s3-object-lambda"}, "operations": { - "AbortMultipartUpload": {"method": "DELETE", "requestUri": "/{Bucket}/{Key+}"}, + "AbortMultipartUpload": {"method": "DELETE", "requestUri": "/{Bucket}/{Key+}", "requires": {"query": ["uploadId"]}}, "CompleteMultipartUpload": {"method": "POST", "requestUri": "/{Bucket}/{Key+}"}, - "CopyObject": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}"}, + "CopyObject": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}", "requires": {"headers": ["x-amz-copy-source"]}}, "CreateBucket": {"method": "PUT", "requestUri": "/{Bucket}"}, "CreateBucketMetadataConfiguration": {"method": "POST", "requestUri": "/{Bucket}?metadataConfiguration"}, "CreateBucketMetadataTableConfiguration": {"method": "POST", "requestUri": "/{Bucket}?metadataTable"}, @@ -2002,19 +2003,19 @@ "GetBucketAbac": {"method": "GET", "requestUri": "/{Bucket}?abac"}, "GetBucketAccelerateConfiguration": {"method": "GET", "requestUri": "/{Bucket}?accelerate"}, "GetBucketAcl": {"method": "GET", "requestUri": "/{Bucket}?acl"}, - "GetBucketAnalyticsConfiguration": {"method": "GET", "requestUri": "/{Bucket}?analytics"}, + "GetBucketAnalyticsConfiguration": {"method": "GET", "requestUri": "/{Bucket}?analytics", "requires": {"query": ["id"]}}, "GetBucketCors": {"method": "GET", "requestUri": "/{Bucket}?cors"}, "GetBucketEncryption": {"method": "GET", "requestUri": "/{Bucket}?encryption"}, - "GetBucketIntelligentTieringConfiguration": {"method": "GET", "requestUri": "/{Bucket}?intelligent-tiering"}, - "GetBucketInventoryConfiguration": {"method": "GET", "requestUri": "/{Bucket}?inventory"}, - "GetBucketLifecycle": {"method": "GET", "requestUri": "/{Bucket}?lifecycle"}, + "GetBucketIntelligentTieringConfiguration": {"method": "GET", "requestUri": "/{Bucket}?intelligent-tiering", "requires": {"query": ["id"]}}, + "GetBucketInventoryConfiguration": {"method": "GET", "requestUri": "/{Bucket}?inventory", "requires": {"query": ["id"]}}, + "GetBucketLifecycle": {"method": "GET", "requestUri": "/{Bucket}?lifecycle", "deprecated": true}, "GetBucketLifecycleConfiguration": {"method": "GET", "requestUri": "/{Bucket}?lifecycle"}, "GetBucketLocation": {"method": "GET", "requestUri": "/{Bucket}?location"}, "GetBucketLogging": {"method": "GET", "requestUri": "/{Bucket}?logging"}, "GetBucketMetadataConfiguration": {"method": "GET", "requestUri": "/{Bucket}?metadataConfiguration"}, "GetBucketMetadataTableConfiguration": {"method": "GET", "requestUri": "/{Bucket}?metadataTable"}, - "GetBucketMetricsConfiguration": {"method": "GET", "requestUri": "/{Bucket}?metrics"}, - "GetBucketNotification": {"method": "GET", "requestUri": "/{Bucket}?notification"}, + "GetBucketMetricsConfiguration": {"method": "GET", "requestUri": "/{Bucket}?metrics", "requires": {"query": ["id"]}}, + "GetBucketNotification": {"method": "GET", "requestUri": "/{Bucket}?notification", "deprecated": true}, "GetBucketNotificationConfiguration": {"method": "GET", "requestUri": "/{Bucket}?notification"}, "GetBucketOwnershipControls": {"method": "GET", "requestUri": "/{Bucket}?ownershipControls"}, "GetBucketPolicy": {"method": "GET", "requestUri": "/{Bucket}?policy"}, @@ -2026,7 +2027,7 @@ "GetBucketWebsite": {"method": "GET", "requestUri": "/{Bucket}?website"}, "GetObject": {"method": "GET", "requestUri": "/{Bucket}/{Key+}"}, "GetObjectAcl": {"method": "GET", "requestUri": "/{Bucket}/{Key+}?acl"}, - "GetObjectAnnotation": {"method": "GET", "requestUri": "/{Bucket}/{Key+}?annotation"}, + "GetObjectAnnotation": {"method": "GET", "requestUri": "/{Bucket}/{Key+}?annotation", "requires": {"query": ["annotationName"]}}, "GetObjectAttributes": {"method": "GET", "requestUri": "/{Bucket}/{Key+}?attributes"}, "GetObjectLegalHold": {"method": "GET", "requestUri": "/{Bucket}/{Key+}?legal-hold"}, "GetObjectLockConfiguration": {"method": "GET", "requestUri": "/{Bucket}?object-lock"}, @@ -2041,13 +2042,12 @@ "ListBucketInventoryConfigurations": {"method": "GET", "requestUri": "/{Bucket}?inventory"}, "ListBucketMetricsConfigurations": {"method": "GET", "requestUri": "/{Bucket}?metrics"}, "ListBuckets": {"method": "GET", "requestUri": "/"}, - "ListDirectoryBuckets": {"method": "GET", "requestUri": "/"}, "ListMultipartUploads": {"method": "GET", "requestUri": "/{Bucket}?uploads"}, "ListObjectAnnotations": {"method": "GET", "requestUri": "/{Bucket}/{Key+}?annotation"}, "ListObjectVersions": {"method": "GET", "requestUri": "/{Bucket}?versions"}, "ListObjects": {"method": "GET", "requestUri": "/{Bucket}"}, "ListObjectsV2": {"method": "GET", "requestUri": "/{Bucket}?list-type=2"}, - "ListParts": {"method": "GET", "requestUri": "/{Bucket}/{Key+}"}, + "ListParts": {"method": "GET", "requestUri": "/{Bucket}/{Key+}", "requires": {"query": ["uploadId"]}}, "PutBucketAbac": {"method": "PUT", "requestUri": "/{Bucket}?abac"}, "PutBucketAccelerateConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?accelerate"}, "PutBucketAcl": {"method": "PUT", "requestUri": "/{Bucket}?acl"}, @@ -2056,11 +2056,11 @@ "PutBucketEncryption": {"method": "PUT", "requestUri": "/{Bucket}?encryption"}, "PutBucketIntelligentTieringConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?intelligent-tiering"}, "PutBucketInventoryConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?inventory"}, - "PutBucketLifecycle": {"method": "PUT", "requestUri": "/{Bucket}?lifecycle"}, + "PutBucketLifecycle": {"method": "PUT", "requestUri": "/{Bucket}?lifecycle", "deprecated": true}, "PutBucketLifecycleConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?lifecycle"}, "PutBucketLogging": {"method": "PUT", "requestUri": "/{Bucket}?logging"}, "PutBucketMetricsConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?metrics"}, - "PutBucketNotification": {"method": "PUT", "requestUri": "/{Bucket}?notification"}, + "PutBucketNotification": {"method": "PUT", "requestUri": "/{Bucket}?notification", "deprecated": true}, "PutBucketNotificationConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?notification"}, "PutBucketOwnershipControls": {"method": "PUT", "requestUri": "/{Bucket}?ownershipControls"}, "PutBucketPolicy": {"method": "PUT", "requestUri": "/{Bucket}?policy"}, @@ -2084,9 +2084,8 @@ "UpdateBucketMetadataInventoryTableConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?metadataInventoryTable"}, "UpdateBucketMetadataJournalTableConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?metadataJournalTable"}, "UpdateObjectEncryption": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}?encryption"}, - "UploadPart": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}"}, - "UploadPartCopy": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}"}, - "WriteGetObjectResponse": {"method": "POST", "requestUri": "/WriteGetObjectResponse"} + "UploadPart": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}", "requires": {"query": ["partNumber", "uploadId"]}}, + "UploadPartCopy": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}", "requires": {"query": ["partNumber", "uploadId"], "headers": ["x-amz-copy-source"]}} } }, "s3control": { diff --git a/src/test/java/io/floci/aws/services/iam/IamRestRoutesTest.java b/src/test/java/io/floci/aws/services/iam/IamRestRoutesTest.java index a0d6b20883..2575e44564 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRestRoutesTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRestRoutesTest.java @@ -210,6 +210,57 @@ class IamRestRoutesTest { query("list-type", "1"))); } + /** + * Operations sharing a route are told apart by what botocore requires their request to carry: S3's UploadPart, on + * {@code PUT /{Bucket}/{Key+}} with PutObject, requires {@code partNumber} and {@code uploadId}, and CopyObject the + * {@code x-amz-copy-source} header. The route requiring more wins when the request carries it all, a header is + * matched whatever its case, and with no headers known a route requiring one cannot be told to match. + */ + @Test + void operationsSharingARouteAreToldApartByWhatTheirRequestMustCarry() { + IamRestRoutes table = routes(""" + {"handRouted": {}, "models": {"objects": {"credentialScope": "obj", "operations": { + "PutObject": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}"}, + "CopyObject": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}", + "requires": {"headers": ["x-amz-copy-source"]}}, + "UploadPart": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}", + "requires": {"query": ["partNumber", "uploadId"]}}, + "UploadPartCopy": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}", + "requires": {"query": ["partNumber", "uploadId"], "headers": ["x-amz-copy-source"]}} + }}}}"""); + MultivaluedMap part = query("partNumber", "1"); + part.add("uploadId", "u"); + MultivaluedMap copy = new MultivaluedHashMap<>(); + copy.add("X-Amz-Copy-Source", "b/k"); + MultivaluedMap none = new MultivaluedHashMap<>(); + assertEquals(Optional.of("PutObject"), operation(table, null, none)); + assertEquals(Optional.of("CopyObject"), operation(table, null, copy)); + assertEquals(Optional.of("UploadPart"), operation(table, part, none)); + assertEquals(Optional.of("UploadPartCopy"), operation(table, part, copy)); + // One of the two query parameters is not enough, and without headers a copy is read as the plain write. + assertEquals(Optional.of("PutObject"), operation(table, query("partNumber", "1"), none)); + assertEquals(Optional.of("PutObject"), table.operation("obj", "PUT", "/b/k", null)); + assertEquals(Optional.of("objects"), table.match("obj", "PUT", "/b/k", null, false, copy) + .map(IamRestRoutes.Match::model)); + } + + /** A deprecated operation yields to the current one of the same route and conditions. */ + @Test + void aDeprecatedOperationYieldsToTheCurrentOneOfItsRoute() { + IamRestRoutes table = routes(""" + {"handRouted": {}, "models": {"objects": {"credentialScope": "obj", "operations": { + "GetBucketLifecycle": {"method": "GET", "requestUri": "/{Bucket}?lifecycle", "deprecated": true}, + "GetBucketLifecycleConfiguration": {"method": "GET", "requestUri": "/{Bucket}?lifecycle"} + }}}}"""); + assertEquals(Optional.of("GetBucketLifecycleConfiguration"), + table.operation("obj", "GET", "/b", query("lifecycle", ""))); + } + + private static Optional operation(IamRestRoutes table, MultivaluedMap query, + MultivaluedMap headers) { + return table.match("obj", "PUT", "/b/k", query, false, headers).map(IamRestRoutes.Match::operation); + } + /** A trailing slash is dropped, as the router drops it, and an encoded slash stays inside its label. */ @Test void aPathIsReadAsTheRouterMatchedIt() { diff --git a/tools/aws/regen_rest_routes.py b/tools/aws/regen_rest_routes.py index f3a6ed1085..8e71e8d37e 100644 --- a/tools/aws/regen_rest_routes.py +++ b/tools/aws/regen_rest_routes.py @@ -10,9 +10,16 @@ A request no rule maps is the operation whose route it matches, checked as the a request on each route and compares the action the registry gives with that one. The credential scopes in `HAND_ROUTED` are authorized by the registry's rules alone, each for its -reason, and their routes are vendored for the coverage test only. Within any other scope, two -operations on one route would leave a request matching it no single operation, so the generation -fails on them. Supported shared-controller alternatives are generated beside the modeled URI, with +reason, and their routes are vendored for the coverage test only. Operations sharing a route are told +apart by what botocore models their requests as carrying: the query parameters and headers of the +members their input requires (`requires`: S3's UploadPart, on `PUT /{Bucket}/{Key+}` with PutObject, +requires `partNumber` and `uploadId`, CopyObject the `x-amz-copy-source` header), and a deprecated +operation (`deprecated`) yields to a current one of the same route and conditions. An operation whose +every request botocore's endpoint rules send to another service's endpoint, signed for it, is that +service's (`signedElsewhere`: S3's ListDirectoryBuckets, signed `s3express`). Within any scope, the +operations of a route must leave every request one operation: no two current ones requiring the same, and +what any two require together required by one of them, the route requiring all a request carries being its +operation (`shared_routes`). The generation fails otherwise. Supported shared-controller alternatives are generated beside the modeled URI, with member-location overrides for the bare route, and its own method where that is not the operation's. These alternatives describe existing Floci compatibility paths, not additional botocore operations. @@ -37,6 +44,7 @@ Run from anywhere in the repo: from __future__ import annotations import argparse +import gzip import json import re import sys @@ -334,8 +342,10 @@ def carried_documented(current: str) -> dict[str, dict]: METHODS = ("GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS") -def build(models: dict[str, dict], provenance: str, documented: dict[str, dict] | None = None) -> dict: - """The vendored document from each loaded model, and the routes of each documented endpoint.""" +def build(models: dict[str, dict], provenance: str, documented: dict[str, dict] | None = None, + elsewhere: dict[str, dict[str, str]] | None = None) -> dict: + """The vendored document from each loaded model, and the routes of each documented endpoint. `elsewhere` gives + each model's operations signed for another service (`signed_elsewhere`).""" routes = {} denial_statuses = {} for name in sorted(models): @@ -344,8 +354,11 @@ def build(models: dict[str, dict], provenance: str, documented: dict[str, dict] raise SystemExit(f"error: {name} is not a REST model") shared = SHARED_ROUTES.get(name, frozenset()) spanning = ARN_SPANNING_ROUTES.get(name, frozenset()) + signed = (elsewhere or {}).get(name, {}) operations = {} for operation in sorted(model["operations"]): + if operation in signed: + continue http = model["operations"][operation]["http"] request_uri = http["requestUri"] if operation in shared or operation in spanning: @@ -361,6 +374,8 @@ def build(models: dict[str, dict], provenance: str, documented: dict[str, dict] "apiVersion": model["metadata"]["apiVersion"], "operations": operations, } + if signed: + routes[name]["signedElsewhere"] = dict(sorted(signed.items())) status = access_denied_status(model) if status is not None: scope = MODELS[name] @@ -373,9 +388,10 @@ def build(models: dict[str, dict], provenance: str, documented: dict[str, dict] raise SystemExit(f"error: {name} is both a botocore model and a documented endpoint") routes[name] = model routes = dict(sorted(routes.items())) + with_conditions(routes, models) shared = shared_routes(routes) if shared: - raise SystemExit("error: one route names more than one operation in a scope the rules do not route alone: " + raise SystemExit("error: one route names more than one operation a request cannot tell apart: " + "; ".join(shared)) return { "_source": { @@ -387,6 +403,79 @@ def build(models: dict[str, dict], provenance: str, documented: dict[str, dict] } +def with_conditions(routes: dict[str, dict], models: dict[str, dict]) -> None: + """Each operation of a route that names several within its scope given what botocore models its request as + carrying: the query parameters and headers of the members its input requires (`requires`), and whether botocore + marks it `deprecated`. One operation in several models of a scope, on one route, is one operation.""" + named: dict[tuple, list[tuple[str, str]]] = {} + for name, model in routes.items(): + for operation, route in model["operations"].items(): + key = (model["credentialScope"],) + route_key(route["method"], route["requestUri"]) + named.setdefault(key, []).append((name, operation)) + for operations in named.values(): + if len({operation for _, operation in operations}) < 2: + continue + for name, operation in operations: + if name not in models: + continue + spec = models[name]["operations"][operation] + shape = models[name].get("shapes", {}).get(spec.get("input", {}).get("shape", ""), {}) + required = set(shape.get("required", [])) + located = [(member.get("location"), member.get("locationName", member_name)) + for member_name, member in shape.get("members", {}).items() if member_name in required] + query = sorted(where for location, where in located if location == "querystring") + headers = sorted(where.lower() for location, where in located if location == "header") + route = routes[name]["operations"][operation] + if query or headers: + route["requires"] = {**({"query": query} if query else {}), **({"headers": headers} if headers else {})} + if spec.get("deprecated"): + route["deprecated"] = True + + +def signed_elsewhere(models: dict[str, dict], rulesets: dict[str, dict], partitions: dict | None) -> dict[str, dict]: + """The operations of each model that botocore's endpoint rules send, for every request, to another service's + endpoint, signed for it: those whose static context parameters (`staticContextParams`) alone choose the endpoint, + no member of their own bound to one (`contextParam`), and whose endpoint's auth scheme names another signing name + than the model's. S3's ListDirectoryBuckets goes to s3express-control, signed `s3express`; WriteGetObjectResponse + to its own endpoint, signed `s3-object-lambda`. Resolved by botocore's own endpoint provider, in us-east-1.""" + if partitions is None: + return {} + from botocore.endpoint_provider import EndpointProvider # pinned botocore (tools/aws/requirements.txt) + found: dict[str, dict[str, str]] = {} + for name, model in sorted(models.items()): + if name not in rulesets: + continue + provider = EndpointProvider(rulesets[name], partitions) + own = model["metadata"].get("signingName", model["metadata"].get("endpointPrefix")) + for operation, spec in sorted(model["operations"].items()): + static = {key: value["value"] for key, value in (spec.get("staticContextParams") or {}).items()} + shape = model.get("shapes", {}).get(spec.get("input", {}).get("shape", ""), {}) + if not static or any("contextParam" in member for member in shape.get("members", {}).values()): + continue + endpoint = provider.resolve_endpoint(Region="us-east-1", **static) + schemes = endpoint.properties.get("authSchemes") or [] + signing = schemes[0].get("signingName", own) if schemes else own + if signing != own: + found.setdefault(name, {})[operation] = signing + return found + + +def load_rulesets(data: Path) -> tuple[dict[str, dict], dict | None]: + """Each model's botocore endpoint rule set, where it has one, and botocore's partitions.""" + rulesets = {} + for name in MODELS: + directory = latest_model_dir(data, name) + for file in ("endpoint-rule-set-1.json", "endpoint-rule-set-1.json.gz"): + path = directory / file + if path.is_file(): + opener = gzip.open if file.endswith(".gz") else open + with opener(path, "rt", encoding="utf-8") as f: + rulesets[name] = json.load(f) + break + partitions = data / "partitions.json" + return rulesets, json.loads(partitions.read_text(encoding="utf-8")) if partitions.is_file() else None + + def bare_tags_route(method: str) -> dict: """The bare `/tags` route SharedTagsController also serves for a shared tags route of the method, with where it reads the ARN: a tagging request is a POST whose body names it, whether the service tags with POST or with @@ -405,18 +494,38 @@ def route_key(method: str, request_uri: str) -> tuple: def shared_routes(routes: dict[str, dict]) -> list[str]: - """The routes that name more than one operation within a scope `HAND_ROUTED` does not name.""" - named: dict[tuple, set[str]] = {} + """The routes that name operations a request cannot tell apart within a scope. Operations of one method, path and + query are told apart by what their requests must carry (`requires`), the route requiring all a request carries + being its operation; so no two of them may require the same, unless all but one are deprecated, and what any two + require together must be what one of them requires: then the operations a request satisfies always include one + requiring all the others do. S3's PutObject, CopyObject (`x-amz-copy-source`), UploadPart (`partNumber` and + `uploadId`) and UploadPartCopy (all three) qualify; two operations requiring `a` and `b`, with none requiring both, + do not.""" + grouped: dict[tuple, dict[frozenset, list[tuple[str, bool]]]] = {} for name, model in routes.items(): - if model["credentialScope"] in HAND_ROUTED: - continue for operation, route in model["operations"].items(): for variant in [route, *route.get("alternatives", [])]: + requires = route.get("requires", {}) if variant is route else {} key = (model["credentialScope"],) + route_key(variant.get("method", route["method"]), variant["requestUri"]) - named.setdefault(key, set()).add(operation) - return [f"{key[0]} {key[1]} {'/'.join(key[2])}: {', '.join(sorted(operations))}" - for key, operations in sorted(named.items()) if len(operations) > 1] + needs = frozenset([f"?{parameter}" for parameter in requires.get("query", [])] + + [f"{header}:" for header in requires.get("headers", [])]) + entry = (operation, variant is route and bool(route.get("deprecated"))) + operations = grouped.setdefault(key, {}).setdefault(needs, []) + if entry not in operations: + operations.append(entry) + found = [] + for key, by_needs in sorted(grouped.items()): + named = sorted({operation for operations in by_needs.values() for operation, _ in operations}) + if len(named) < 2: + continue + same = [operations for operations in by_needs.values() + if len({operation for operation, _ in operations}) > 1 + and len({operation for operation, deprecated in operations if not deprecated}) != 1] + unjoined = [(a, b) for a in by_needs for b in by_needs if (a | b) not in by_needs] + if same or unjoined: + found.append(f"{key[0]} {key[1]} {'/'.join(key[2])}: {', '.join(named)}") + return found def load_models(data: Path) -> dict[str, dict]: @@ -439,6 +548,8 @@ def render(doc: dict) -> str: lines.append(f' "accessDeniedStatus": {model["accessDeniedStatus"]},') if "documented" in model: lines.append(f' "documented": {json.dumps(model["documented"])},') + if "signedElsewhere" in model: + lines.append(f' "signedElsewhere": {json.dumps(model["signedElsewhere"])},') lines.append(' "operations": {') operations = list(model["operations"].items()) for position, (operation, route) in enumerate(operations): @@ -486,7 +597,9 @@ def main(argv: list[str] | None = None) -> int: documented = {name: build_documented(spec) for name, spec in DOCUMENTED.items()} if args.fetch_documented \ else carried_documented(current) data, provenance = resolve_botocore_data(args.botocore_data) - fresh = render(build(load_models(data), provenance, documented)) + models = load_models(data) + rulesets, partitions = load_rulesets(data) + fresh = render(build(models, provenance, documented, signed_elsewhere(models, rulesets, partitions))) if args.check: if strip_source(current) != strip_source(fresh): diff --git a/tools/aws/test_regen_rest_routes.py b/tools/aws/test_regen_rest_routes.py index 4bef6dd2f5..62929223a1 100644 --- a/tools/aws/test_regen_rest_routes.py +++ b/tools/aws/test_regen_rest_routes.py @@ -19,6 +19,21 @@ def model(protocol: str, api_version: str, **operations: tuple[str, str]) -> dic } +def shaped(model_doc: dict, operation: str, required: dict[str, tuple[str, str]], deprecated: bool = False) -> dict: + """The model with the operation's input requiring each member, at its location under its name on the wire.""" + shape = f"{operation}Request" + model_doc.setdefault("shapes", {})[shape] = { + "type": "structure", "required": sorted(required), + "members": {member: {"shape": "String", "location": location, "locationName": wire} + for member, (location, wire) in required.items()}, + } + model_doc["shapes"]["String"] = {"type": "string"} + model_doc["operations"][operation]["input"] = {"shape": shape} + if deprecated: + model_doc["operations"][operation]["deprecated"] = True + return model_doc + + def test_each_operation_keeps_its_method_and_request_uri_under_its_scope(): doc = r.build({ "s3": model("rest-xml", "2006-03-01", GetObject=("GET", "/{Bucket}/{Key+}?x-id=GetObject"), @@ -70,21 +85,109 @@ def test_check_passes_on_a_fresh_generation_and_fails_on_a_stale_one(tmp_path, m assert r.main(data + ["--check"]) == 1 -def test_a_route_naming_two_operations_of_a_scope_the_rules_do_not_route_alone_is_refused(): +def test_a_route_naming_two_operations_a_request_cannot_tell_apart_is_refused(): with pytest.raises(SystemExit): r.build({"lambda": model("rest-json", "2015-03-31", GetByName=("GET", "/things/{Name}"), GetById=("GET", "/things/{Id}/"))}, "botocore test") - # One operation in two models of a scope, two routes a query tells apart, and two operations on one route of a - # scope the rules route alone, all pass. + # A scope the rules route alone is checked too: its routes are what the coverage test builds requests on. + with pytest.raises(SystemExit): + r.build({"s3": model("rest-xml", "2006-03-01", PutObject=("PUT", "/{Bucket}/{Key+}"), + UploadPart=("PUT", "/{Bucket}/{Key+}"))}, "botocore test") + # One operation in two models of a scope, two routes a query tells apart, and two operations on one route that + # what botocore requires tells apart, all pass. doc = r.build({ "lambda": model("rest-json", "2015-03-31", ListTags=("GET", "/tags/{ARN}"), GetThing=("GET", "/things/{Name}"), ListThingTags=("GET", "/things/{Name}?tagging")), "lambda-microvms": model("rest-json", "2025-01-01", ListTags=("GET", "/tags/{Resource}")), - "s3": model("rest-xml", "2006-03-01", PutObject=("PUT", "/{Bucket}/{Key+}"), - UploadPart=("PUT", "/{Bucket}/{Key+}")), + "s3": shaped(model("rest-xml", "2006-03-01", PutObject=("PUT", "/{Bucket}/{Key+}"), + UploadPart=("PUT", "/{Bucket}/{Key+}")), "UploadPart", + {"PartNumber": ("querystring", "partNumber"), "UploadId": ("querystring", "uploadId")}), }, "botocore test") assert doc["handRouted"] == dict(sorted(r.HAND_ROUTED.items())) assert set(doc["handRouted"]) == {"s3"} + # Only a route several operations share carries conditions; one operation in two models is one operation. + assert "requires" not in doc["models"]["lambda"]["operations"]["ListTags"] + assert "requires" not in doc["models"]["lambda"]["operations"]["GetThing"] + + +def test_operations_sharing_a_route_carry_the_query_parameters_and_headers_botocore_requires(): + s3 = model("rest-xml", "2006-03-01", PutObject=("PUT", "/{Bucket}/{Key+}"), CopyObject=("PUT", "/{Bucket}/{Key+}"), + UploadPart=("PUT", "/{Bucket}/{Key+}"), UploadPartCopy=("PUT", "/{Bucket}/{Key+}")) + shaped(s3, "CopyObject", {"CopySource": ("header", "x-amz-copy-source")}) + shaped(s3, "UploadPart", {"PartNumber": ("querystring", "partNumber"), "UploadId": ("querystring", "uploadId")}) + shaped(s3, "UploadPartCopy", {"CopySource": ("header", "x-amz-copy-source"), + "PartNumber": ("querystring", "partNumber"), "UploadId": ("querystring", "uploadId")}) + operations = r.build({"s3": s3}, "botocore test")["models"]["s3"]["operations"] + assert "requires" not in operations["PutObject"] + assert operations["CopyObject"]["requires"] == {"headers": ["x-amz-copy-source"]} + assert operations["UploadPart"]["requires"] == {"query": ["partNumber", "uploadId"]} + assert operations["UploadPartCopy"]["requires"] == {"query": ["partNumber", "uploadId"], + "headers": ["x-amz-copy-source"]} + + +def test_what_any_two_operations_of_a_route_require_together_must_be_what_one_of_them_requires(): + # A request carrying both `a` and `b` would satisfy both operations, and none requires all it carries. + route = model("rest-xml", "2006-03-01", WithA=("PUT", "/{Bucket}/{Key+}"), WithB=("PUT", "/{Bucket}/{Key+}")) + shaped(route, "WithA", {"A": ("querystring", "a")}) + shaped(route, "WithB", {"B": ("header", "x-b")}) + with pytest.raises(SystemExit): + r.build({"s3": route}, "botocore test") + # An operation requiring both settles it, as UploadPartCopy settles CopyObject's header and UploadPart's query. + route["operations"]["WithBoth"] = {"http": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}"}} + shaped(route, "WithBoth", {"A": ("querystring", "a"), "B": ("header", "x-b")}) + assert set(r.build({"s3": route}, "botocore test")["models"]["s3"]["operations"]) == {"WithA", "WithB", "WithBoth"} + + +def test_a_deprecated_operation_yields_to_the_current_one_of_its_route_and_conditions(): + s3 = model("rest-xml", "2006-03-01", GetBucketLifecycle=("GET", "/{Bucket}?lifecycle"), + GetBucketLifecycleConfiguration=("GET", "/{Bucket}?lifecycle")) + operations = r.build({"s3": shaped(s3, "GetBucketLifecycle", {}, deprecated=True)}, + "botocore test")["models"]["s3"]["operations"] + assert operations["GetBucketLifecycle"]["deprecated"] is True + assert "deprecated" not in operations["GetBucketLifecycleConfiguration"] + # Two deprecated ones, or two current ones, a request still cannot tell apart. + both = model("rest-xml", "2006-03-01", GetBucketLifecycle=("GET", "/{Bucket}?lifecycle"), + GetBucketLifecycleConfiguration=("GET", "/{Bucket}?lifecycle")) + shaped(both, "GetBucketLifecycle", {}, deprecated=True) + shaped(both, "GetBucketLifecycleConfiguration", {}, deprecated=True) + with pytest.raises(SystemExit): + r.build({"s3": both}, "botocore test") + + +def test_an_operation_signed_for_another_service_on_every_request_is_left_out_of_the_scope(): + from botocore.loaders import Loader + partitions = Loader().load_data("partitions") + ruleset = { + "version": "1.0", + "parameters": {"Region": {"type": "String", "builtIn": "AWS::Region"}, + "UseOtherControl": {"type": "Boolean"}, "Bucket": {"type": "String"}}, + "rules": [ + {"type": "endpoint", "conditions": [{"fn": "booleanEquals", "argv": [{"ref": "UseOtherControl"}, True]}], + "endpoint": {"url": "https://other-control.example", + "properties": {"authSchemes": [{"name": "sigv4", "signingName": "other"}]}}}, + {"type": "endpoint", "conditions": [], + "endpoint": {"url": "https://s3.example", + "properties": {"authSchemes": [{"name": "sigv4", "signingName": "s3"}]}}}, + ], + } + s3 = model("rest-xml", "2006-03-01", ListBuckets=("GET", "/"), ListOtherBuckets=("GET", "/"), + CreateBucket=("PUT", "/{Bucket}")) + s3["metadata"]["signingName"] = "s3" + s3["operations"]["ListOtherBuckets"]["staticContextParams"] = {"UseOtherControl": {"value": True}} + # A member of its own bound to an endpoint parameter decides the endpoint per request: not every request's. + s3["operations"]["CreateBucket"]["staticContextParams"] = {"UseOtherControl": {"value": True}} + shaped(s3, "CreateBucket", {"Bucket": ("uri", "Bucket")}) + s3["shapes"]["CreateBucketRequest"]["members"]["Bucket"]["contextParam"] = {"name": "Bucket"} + + elsewhere = r.signed_elsewhere({"s3": s3}, {"s3": ruleset}, partitions) + assert elsewhere == {"s3": {"ListOtherBuckets": "other"}} + doc = r.build({"s3": s3}, "botocore test", elsewhere=elsewhere) + assert set(doc["models"]["s3"]["operations"]) == {"ListBuckets", "CreateBucket"} + assert doc["models"]["s3"]["signedElsewhere"] == {"ListOtherBuckets": "other"} + assert '"signedElsewhere": {"ListOtherBuckets": "other"}' in r.render(doc) + # Without it, GET / names two operations a request cannot tell apart. + with pytest.raises(SystemExit): + r.build({"s3": s3}, "botocore test") def test_the_hand_routed_scopes_are_rendered_with_their_reasons():