diff --git a/src/main/java/io/floci/aws/core/common/SignedServiceRoute.java b/src/main/java/io/floci/aws/core/common/SignedServiceRoute.java index fa61056a43..79cc0ee7b1 100644 --- a/src/main/java/io/floci/aws/core/common/SignedServiceRoute.java +++ b/src/main/java/io/floci/aws/core/common/SignedServiceRoute.java @@ -23,9 +23,16 @@ import java.util.function.Predicate; * straight to it that is not signed for the service is refused the way S3 refuses that bucket * name, since an S3 bucket name may not begin with an underscore, rather than reaching the * service. + * + *

A request routed under the prefix, rewritten onto it or sent to it, records the prefix + * ({@link #internalPrefix}), so IAM matches it on the path the service's model gives the + * operation: the path it was routed under, without the prefix. */ public final class SignedServiceRoute { + /** The request property that holds the internal prefix a request was routed under. */ + public static final String INTERNAL_PREFIX_PROPERTY = SignedServiceRoute.class.getName() + ".internalPrefix"; + private final ResolvedServiceCatalog catalog; private final Set externalKeys; private final String internalPrefix; @@ -80,6 +87,15 @@ public final class SignedServiceRoute { ResteasyRequests.queryParameters(ctx).getFirst("X-Amz-Credential"))); } + /** + * The internal prefix a request was routed under, as {@link #apply} recorded it: empty for a + * request no route moved onto one or sent to one. + */ + public static Optional internalPrefix(ContainerRequestContext ctx) { + return ctx.getProperty(INTERNAL_PREFIX_PROPERTY) instanceof String prefix ? Optional.of(prefix) + : Optional.empty(); + } + public void apply(ContainerRequestContext ctx) { String path = ctx.getUriInfo().getPath(); String normalizedPath = path.startsWith("/") ? path : "/" + path; @@ -87,7 +103,9 @@ public final class SignedServiceRoute { if (internalPaths.test(normalizedPath)) { if (!signedForService(ctx)) { ctx.abortWith(invalidBucketName()); + return; } + ctx.setProperty(INTERNAL_PREFIX_PROPERTY, internalPrefix); return; } if (!publicPaths.test(normalizedPath) || !signedForService(ctx)) { @@ -96,6 +114,7 @@ public final class SignedServiceRoute { ctx.setRequestUri(ctx.getUriInfo().getRequestUriBuilder() .replacePath(internalPrefix + normalizedPath) .build()); + ctx.setProperty(INTERNAL_PREFIX_PROPERTY, internalPrefix); } private boolean signedForService(ContainerRequestContext ctx) { 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 27d7921940..c8d74d9f63 100644 --- a/src/main/java/io/floci/aws/services/iam/IamActionRegistry.java +++ b/src/main/java/io/floci/aws/services/iam/IamActionRegistry.java @@ -7,6 +7,7 @@ import io.floci.aws.core.common.IamOperation; import io.floci.aws.core.common.ProtocolClaim; import io.floci.aws.core.common.RequestResources; import io.floci.aws.core.common.ResteasyRequests; +import io.floci.aws.core.common.SignedServiceRoute; import io.floci.aws.core.common.WireProtocol; import io.floci.aws.services.dynamodb.DynamoDbPartiQLParser; import io.floci.aws.services.eks.EksController; @@ -696,9 +697,10 @@ public class IamActionRegistry { * matches, and is checked as that operation's action ({@link IamAuthorizedActions#actionFor}), as a * request naming its operation is, when Floci can check it as AWS does ({@code checkedAsAws}). One it * cannot is left unmapped rather than checked on {@code *}, which would refuse a grant scoped to the - * resource AWS checks it on. The scopes the vendored routes list as hand-routed, S3's and API Gateway's, - * have their rules alone. Returns {@code null} when nothing maps the request (caller treats this as - * ALLOW). + * resource AWS checks it on. A request a route filter moved under an internal prefix is matched on its + * path without the prefix ({@link #withoutInternalPrefix}), the path the model gives it. The scopes the + * vendored routes list as hand-routed, S3's and API Gateway's, have their rules alone. Returns + * {@code null} when nothing maps the request (caller treats this as ALLOW). */ public String resolveRoute(String credentialScope, ContainerRequestContext ctx) { String method = ctx.getMethod().toUpperCase(); @@ -731,8 +733,8 @@ public class IamActionRegistry { return rule.action(); } } - Optional operation = restRoutes.operation(credentialScope, method, path, - ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters()); + Optional operation = restRoutes.operation(credentialScope, method, withoutInternalPrefix(ctx, path), + ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters(), movedUnderPrefix(ctx)); if (operation.isPresent()) { String action = IamAuthorizedActions.actionFor(credentialScope, operation.get()); if (checkedAsAws(credentialScope, operation.get(), action)) { @@ -759,8 +761,8 @@ public class IamActionRegistry { if (credentialScope == null || !routes.routes(credentialScope)) { return Map.of(); } - return routes.match(credentialScope, ctx.getMethod().toUpperCase(), routedPath(ctx), - ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters()) + return routes.match(credentialScope, ctx.getMethod().toUpperCase(), withoutInternalPrefix(ctx, routedPath(ctx)), + ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters(), movedUnderPrefix(ctx)) .map(IamRestRoutes.Match::labels).orElse(Map.of()); } @@ -772,7 +774,8 @@ public class IamActionRegistry { return Map.of(); } return IamRestRoutes.vendored().match(operation.substring(0, separator), ctx.getMethod().toUpperCase(), - routedPath(ctx), ctx.getUriInfo().getQueryParameters()) + withoutInternalPrefix(ctx, routedPath(ctx)), ctx.getUriInfo().getQueryParameters(), + movedUnderPrefix(ctx)) .filter(match -> match.operation().equals(operation.substring(separator + 1))) .map(IamRestRoutes.Match::located).orElse(Map.of()); } @@ -841,6 +844,23 @@ public class IamActionRegistry { return withoutTrailingSlash(rawPath(ctx)); } + /** + * The path without the internal prefix a route filter moved the request under ({@link SignedServiceRoute}), which + * is the path the service's model gives the operation and the vendored routes hold; the path itself when it was + * moved under none. + */ + static String withoutInternalPrefix(ContainerRequestContext ctx, String path) { + return SignedServiceRoute.internalPrefix(ctx) + .filter(prefix -> path.equals(prefix) || path.startsWith(prefix + "/")) + .map(prefix -> path.length() == prefix.length() ? "/" : path.substring(prefix.length())) + .orElse(path); + } + + /** Whether a route filter moved the request under an internal prefix, so the router matched its path decoded. */ + private static boolean movedUnderPrefix(ContainerRequestContext ctx) { + return SignedServiceRoute.internalPrefix(ctx).isPresent(); + } + /** The path without its trailing slashes, the root's own kept. */ static String withoutTrailingSlash(String path) { String trimmed = path; 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 03b1ef7f1f..cabf53eb77 100644 --- a/src/main/java/io/floci/aws/services/iam/IamRestRoutes.java +++ b/src/main/java/io/floci/aws/services/iam/IamRestRoutes.java @@ -34,6 +34,12 @@ import java.util.regex.Pattern; * is the most specific one's operation: compared segment by segment from the left, a literal before a segment mixing * a literal and a label, before a label, before a greedy label, then the route naming more of the query. * + *

A request a route filter moved under an internal prefix ({@code SignedServiceRoute}) is matched on its path + * without the prefix, which is the path the model gives its operation. The router matched it decoded, so a label's + * value holds the slashes its encoding hid (a key ARN on the Payment Cryptography data plane), and the controller's + * route takes them: a path that matches no route with each label taking one segment is matched again with each + * label taking as many as its value spans. + * *

The file is generated by {@code tools/aws/regen_rest_routes.py}, which fails when one route names two * operations of a credential scope read here. The scopes it lists as {@code handRouted} are not read: the * registry's rules authorize them alone. A missing or malformed resource is a build defect, so loading fails with @@ -62,11 +68,16 @@ final class IamRestRoutes { * A route: its operation, its path as a pattern capturing each label in turn, the labels' names, each segment's * rank, and the query it names. */ - private record Route(String operation, Pattern path, List labels, int[] ranks, Map query, - Map located) { + private record Route(String operation, Pattern path, Pattern spanning, List labels, int[] ranks, + Map query, Map located) { - boolean matches(String requestPath, MultivaluedMap parameters) { - if (!path.matcher(requestPath).matches()) { + /** The route's pattern: each label taking one segment, or, spanning, the segments its value spans. */ + Pattern pattern(boolean spanned) { + return spanned ? spanning : path; + } + + boolean matches(String requestPath, MultivaluedMap parameters, boolean spanned) { + if (!pattern(spanned).matcher(requestPath).matches()) { return false; } for (Map.Entry parameter : query.entrySet()) { @@ -79,8 +90,8 @@ final class IamRestRoutes { } /** The value the path gives each label, decoded as the router decodes a path parameter. */ - Map labelValues(String requestPath) { - Matcher matcher = path.matcher(requestPath); + Map labelValues(String requestPath, boolean spanned) { + Matcher matcher = pattern(spanned).matcher(requestPath); if (!matcher.matches()) { return Map.of(); } @@ -126,16 +137,38 @@ final class IamRestRoutes { return match(scope, method, path, query).map(Match::operation); } + /** + * As {@link #operation}, for a path a route filter moved under an internal prefix, given without it: when it + * matches no route, its labels may span the slashes their decoded values hold. + */ + Optional operation(String scope, String method, String path, MultivaluedMap query, + boolean movedUnderPrefix) { + return match(scope, method, path, query, movedUnderPrefix).map(Match::operation); + } + /** As {@link #operation}, with the values the request's path gives the route's labels. */ Optional match(String scope, String method, String path, MultivaluedMap query) { + return match(scope, method, path, query, false); + } + + /** As {@link #operation(String, String, String, MultivaluedMap, boolean)}, with the label values. */ + Optional match(String scope, String method, String path, MultivaluedMap query, + boolean movedUnderPrefix) { String requestPath = IamActionRegistry.withoutTrailingSlash(path); + Optional match = best(scope, method, requestPath, query, false); + return match.isPresent() || !movedUnderPrefix ? match : best(scope, method, requestPath, query, true); + } + + private Optional best(String scope, String method, String requestPath, MultivaluedMap query, + boolean spanned) { Route best = null; for (Route route : routes.getOrDefault(scope, Map.of()).getOrDefault(method, List.of())) { - if (route.matches(requestPath, query) && (best == null || route.outranks(best))) { + if (route.matches(requestPath, query, spanned) && (best == null || route.outranks(best))) { best = route; } } - return best == null ? Optional.empty() : Optional.of(new Match(best.operation(), best.labelValues(requestPath), best.located())); + return best == null ? Optional.empty() + : Optional.of(new Match(best.operation(), best.labelValues(requestPath, spanned), best.located())); } /** The modelled denial status, or the existing protocol default when the model declares none. */ @@ -231,13 +264,16 @@ final class IamRestRoutes { String path = IamActionRegistry.withoutTrailingSlash(question < 0 ? requestUri : requestUri.substring(0, question)); List segments = path.equals("/") ? List.of() : List.of(path.substring(1).split("/", -1)); StringBuilder pattern = new StringBuilder(); + StringBuilder spanning = new StringBuilder(); List labels = new ArrayList<>(); int[] ranks = new int[segments.size()]; for (int i = 0; i < segments.size(); i++) { String segment = segments.get(i); pattern.append('/'); + spanning.append('/'); if (GREEDY.matcher(segment).matches()) { pattern.append("(.+)"); + spanning.append("(.+)"); labels.add(segment.substring(1, segment.length() - 2)); ranks[i] = REST_OF_PATH; continue; @@ -247,11 +283,13 @@ final class IamRestRoutes { boolean labelled = false; while (label.find()) { pattern.append(Pattern.quote(segment.substring(literalFrom, label.start()))).append("([^/]+)"); + spanning.append(Pattern.quote(segment.substring(literalFrom, label.start()))).append("(.+)"); labels.add(segment.substring(label.start() + 1, label.end() - 1)); literalFrom = label.end(); labelled = true; } pattern.append(Pattern.quote(segment.substring(literalFrom))).append(MATRIX); + spanning.append(Pattern.quote(segment.substring(literalFrom))).append(MATRIX); ranks[i] = !labelled ? LITERAL : LABEL.matcher(segment).matches() ? ONE_SEGMENT : MIXED; } Map query = new LinkedHashMap<>(); @@ -262,7 +300,8 @@ final class IamRestRoutes { equals < 0 ? "" : parameter.substring(equals + 1)); } } - return new Route(operation, Pattern.compile(pattern.isEmpty() ? "/" : pattern.toString()), List.copyOf(labels), - ranks, Map.copyOf(query), located); + return new Route(operation, Pattern.compile(pattern.isEmpty() ? "/" : pattern.toString()), + Pattern.compile(spanning.isEmpty() ? "/" : spanning.toString()), List.copyOf(labels), ranks, + Map.copyOf(query), located); } } diff --git a/src/main/resources/aws/rest-routes.json b/src/main/resources/aws/rest-routes.json index bcb621c6d4..67c16053a2 100644 --- a/src/main/resources/aws/rest-routes.json +++ b/src/main/resources/aws/rest-routes.json @@ -1264,21 +1264,21 @@ "apiVersion": "2022-02-03", "accessDeniedStatus": 403, "operations": { - "DecryptData": {"method": "POST", "requestUri": "/_paymentcryptography/keys/{KeyIdentifier+}/decrypt"}, - "EncryptData": {"method": "POST", "requestUri": "/_paymentcryptography/keys/{KeyIdentifier+}/encrypt"}, - "GenerateAs2805KekValidation": {"method": "POST", "requestUri": "/_paymentcryptography/as2805kekvalidation/generate"}, - "GenerateAuthRequestCryptogram": {"method": "POST", "requestUri": "/_paymentcryptography/cryptogram/generate"}, - "GenerateCardValidationData": {"method": "POST", "requestUri": "/_paymentcryptography/cardvalidationdata/generate"}, - "GenerateMac": {"method": "POST", "requestUri": "/_paymentcryptography/mac/generate"}, - "GenerateMacEmvPinChange": {"method": "POST", "requestUri": "/_paymentcryptography/macemvpinchange/generate"}, - "GeneratePinData": {"method": "POST", "requestUri": "/_paymentcryptography/pindata/generate"}, - "ReEncryptData": {"method": "POST", "requestUri": "/_paymentcryptography/keys/{IncomingKeyIdentifier+}/reencrypt"}, - "TranslateKeyMaterial": {"method": "POST", "requestUri": "/_paymentcryptography/keymaterial/translate"}, - "TranslatePinData": {"method": "POST", "requestUri": "/_paymentcryptography/pindata/translate"}, - "VerifyAuthRequestCryptogram": {"method": "POST", "requestUri": "/_paymentcryptography/cryptogram/verify"}, - "VerifyCardValidationData": {"method": "POST", "requestUri": "/_paymentcryptography/cardvalidationdata/verify"}, - "VerifyMac": {"method": "POST", "requestUri": "/_paymentcryptography/mac/verify"}, - "VerifyPinData": {"method": "POST", "requestUri": "/_paymentcryptography/pindata/verify"} + "DecryptData": {"method": "POST", "requestUri": "/keys/{KeyIdentifier}/decrypt"}, + "EncryptData": {"method": "POST", "requestUri": "/keys/{KeyIdentifier}/encrypt"}, + "GenerateAs2805KekValidation": {"method": "POST", "requestUri": "/as2805kekvalidation/generate"}, + "GenerateAuthRequestCryptogram": {"method": "POST", "requestUri": "/cryptogram/generate"}, + "GenerateCardValidationData": {"method": "POST", "requestUri": "/cardvalidationdata/generate"}, + "GenerateMac": {"method": "POST", "requestUri": "/mac/generate"}, + "GenerateMacEmvPinChange": {"method": "POST", "requestUri": "/macemvpinchange/generate"}, + "GeneratePinData": {"method": "POST", "requestUri": "/pindata/generate"}, + "ReEncryptData": {"method": "POST", "requestUri": "/keys/{IncomingKeyIdentifier}/reencrypt"}, + "TranslateKeyMaterial": {"method": "POST", "requestUri": "/keymaterial/translate"}, + "TranslatePinData": {"method": "POST", "requestUri": "/pindata/translate"}, + "VerifyAuthRequestCryptogram": {"method": "POST", "requestUri": "/cryptogram/verify"}, + "VerifyCardValidationData": {"method": "POST", "requestUri": "/cardvalidationdata/verify"}, + "VerifyMac": {"method": "POST", "requestUri": "/mac/verify"}, + "VerifyPinData": {"method": "POST", "requestUri": "/pindata/verify"} } }, "pipes": { @@ -1982,23 +1982,23 @@ "apiVersion": "2017-08-25", "accessDeniedStatus": 403, "operations": { - "AddProfilePermission": {"method": "POST", "requestUri": "/_signer/signing-profiles/{profileName}/permissions"}, - "CancelSigningProfile": {"method": "DELETE", "requestUri": "/_signer/signing-profiles/{profileName}"}, - "DescribeSigningJob": {"method": "GET", "requestUri": "/_signer/signing-jobs/{jobId}"}, - "GetRevocationStatus": {"method": "GET", "requestUri": "/_signer/revocations"}, - "GetSigningPlatform": {"method": "GET", "requestUri": "/_signer/signing-platforms/{platformId}"}, - "GetSigningProfile": {"method": "GET", "requestUri": "/_signer/signing-profiles/{profileName}"}, - "ListProfilePermissions": {"method": "GET", "requestUri": "/_signer/signing-profiles/{profileName}/permissions"}, - "ListSigningJobs": {"method": "GET", "requestUri": "/_signer/signing-jobs"}, - "ListSigningPlatforms": {"method": "GET", "requestUri": "/_signer/signing-platforms"}, - "ListSigningProfiles": {"method": "GET", "requestUri": "/_signer/signing-profiles"}, + "AddProfilePermission": {"method": "POST", "requestUri": "/signing-profiles/{profileName}/permissions"}, + "CancelSigningProfile": {"method": "DELETE", "requestUri": "/signing-profiles/{profileName}"}, + "DescribeSigningJob": {"method": "GET", "requestUri": "/signing-jobs/{jobId}"}, + "GetRevocationStatus": {"method": "GET", "requestUri": "/revocations"}, + "GetSigningPlatform": {"method": "GET", "requestUri": "/signing-platforms/{platformId}"}, + "GetSigningProfile": {"method": "GET", "requestUri": "/signing-profiles/{profileName}"}, + "ListProfilePermissions": {"method": "GET", "requestUri": "/signing-profiles/{profileName}/permissions"}, + "ListSigningJobs": {"method": "GET", "requestUri": "/signing-jobs"}, + "ListSigningPlatforms": {"method": "GET", "requestUri": "/signing-platforms"}, + "ListSigningProfiles": {"method": "GET", "requestUri": "/signing-profiles"}, "ListTagsForResource": {"method": "GET", "requestUri": "/tags/{resourceArn+}", "alternatives": [{"requestUri": "/tags", "located": {"resourceArn": "?resourceArn"}}]}, - "PutSigningProfile": {"method": "PUT", "requestUri": "/_signer/signing-profiles/{profileName}"}, - "RemoveProfilePermission": {"method": "DELETE", "requestUri": "/_signer/signing-profiles/{profileName}/permissions/{statementId}"}, - "RevokeSignature": {"method": "PUT", "requestUri": "/_signer/signing-jobs/{jobId}/revoke"}, - "RevokeSigningProfile": {"method": "PUT", "requestUri": "/_signer/signing-profiles/{profileName}/revoke"}, - "SignPayload": {"method": "POST", "requestUri": "/_signer/signing-jobs/with-payload"}, - "StartSigningJob": {"method": "POST", "requestUri": "/_signer/signing-jobs"}, + "PutSigningProfile": {"method": "PUT", "requestUri": "/signing-profiles/{profileName}"}, + "RemoveProfilePermission": {"method": "DELETE", "requestUri": "/signing-profiles/{profileName}/permissions/{statementId}"}, + "RevokeSignature": {"method": "PUT", "requestUri": "/signing-jobs/{jobId}/revoke"}, + "RevokeSigningProfile": {"method": "PUT", "requestUri": "/signing-profiles/{profileName}/revoke"}, + "SignPayload": {"method": "POST", "requestUri": "/signing-jobs/with-payload"}, + "StartSigningJob": {"method": "POST", "requestUri": "/signing-jobs"}, "TagResource": {"method": "POST", "requestUri": "/tags/{resourceArn+}", "alternatives": [{"requestUri": "/tags", "located": {"resourceArn": "body"}}]}, "UntagResource": {"method": "DELETE", "requestUri": "/tags/{resourceArn+}", "alternatives": [{"requestUri": "/tags", "located": {"resourceArn": "?resourceArn"}}]} } @@ -2007,44 +2007,44 @@ "credentialScope": "xray", "apiVersion": "2016-04-12", "operations": { - "BatchGetTraces": {"method": "POST", "requestUri": "/_xray/Traces"}, - "CancelTraceRetrieval": {"method": "POST", "requestUri": "/_xray/CancelTraceRetrieval"}, - "CreateGroup": {"method": "POST", "requestUri": "/_xray/CreateGroup"}, - "CreateSamplingRule": {"method": "POST", "requestUri": "/_xray/CreateSamplingRule"}, - "DeleteGroup": {"method": "POST", "requestUri": "/_xray/DeleteGroup"}, - "DeleteResourcePolicy": {"method": "POST", "requestUri": "/_xray/DeleteResourcePolicy"}, - "DeleteSamplingRule": {"method": "POST", "requestUri": "/_xray/DeleteSamplingRule"}, - "GetEncryptionConfig": {"method": "POST", "requestUri": "/_xray/EncryptionConfig"}, - "GetGroup": {"method": "POST", "requestUri": "/_xray/GetGroup"}, - "GetGroups": {"method": "POST", "requestUri": "/_xray/Groups"}, - "GetIndexingRules": {"method": "POST", "requestUri": "/_xray/GetIndexingRules"}, - "GetInsight": {"method": "POST", "requestUri": "/_xray/Insight"}, - "GetInsightEvents": {"method": "POST", "requestUri": "/_xray/InsightEvents"}, - "GetInsightImpactGraph": {"method": "POST", "requestUri": "/_xray/InsightImpactGraph"}, - "GetInsightSummaries": {"method": "POST", "requestUri": "/_xray/InsightSummaries"}, - "GetRetrievedTracesGraph": {"method": "POST", "requestUri": "/_xray/GetRetrievedTracesGraph"}, - "GetSamplingRules": {"method": "POST", "requestUri": "/_xray/GetSamplingRules"}, - "GetSamplingStatisticSummaries": {"method": "POST", "requestUri": "/_xray/SamplingStatisticSummaries"}, - "GetSamplingTargets": {"method": "POST", "requestUri": "/_xray/SamplingTargets"}, - "GetServiceGraph": {"method": "POST", "requestUri": "/_xray/ServiceGraph"}, - "GetTimeSeriesServiceStatistics": {"method": "POST", "requestUri": "/_xray/TimeSeriesServiceStatistics"}, - "GetTraceGraph": {"method": "POST", "requestUri": "/_xray/TraceGraph"}, - "GetTraceSegmentDestination": {"method": "POST", "requestUri": "/_xray/GetTraceSegmentDestination"}, - "GetTraceSummaries": {"method": "POST", "requestUri": "/_xray/TraceSummaries"}, - "ListResourcePolicies": {"method": "POST", "requestUri": "/_xray/ListResourcePolicies"}, - "ListRetrievedTraces": {"method": "POST", "requestUri": "/_xray/ListRetrievedTraces"}, - "ListTagsForResource": {"method": "POST", "requestUri": "/_xray/ListTagsForResource"}, - "PutEncryptionConfig": {"method": "POST", "requestUri": "/_xray/PutEncryptionConfig"}, - "PutResourcePolicy": {"method": "POST", "requestUri": "/_xray/PutResourcePolicy"}, - "PutTelemetryRecords": {"method": "POST", "requestUri": "/_xray/TelemetryRecords"}, - "PutTraceSegments": {"method": "POST", "requestUri": "/_xray/TraceSegments"}, - "StartTraceRetrieval": {"method": "POST", "requestUri": "/_xray/StartTraceRetrieval"}, - "TagResource": {"method": "POST", "requestUri": "/_xray/TagResource"}, - "UntagResource": {"method": "POST", "requestUri": "/_xray/UntagResource"}, - "UpdateGroup": {"method": "POST", "requestUri": "/_xray/UpdateGroup"}, - "UpdateIndexingRule": {"method": "POST", "requestUri": "/_xray/UpdateIndexingRule"}, - "UpdateSamplingRule": {"method": "POST", "requestUri": "/_xray/UpdateSamplingRule"}, - "UpdateTraceSegmentDestination": {"method": "POST", "requestUri": "/_xray/UpdateTraceSegmentDestination"} + "BatchGetTraces": {"method": "POST", "requestUri": "/Traces"}, + "CancelTraceRetrieval": {"method": "POST", "requestUri": "/CancelTraceRetrieval"}, + "CreateGroup": {"method": "POST", "requestUri": "/CreateGroup"}, + "CreateSamplingRule": {"method": "POST", "requestUri": "/CreateSamplingRule"}, + "DeleteGroup": {"method": "POST", "requestUri": "/DeleteGroup"}, + "DeleteResourcePolicy": {"method": "POST", "requestUri": "/DeleteResourcePolicy"}, + "DeleteSamplingRule": {"method": "POST", "requestUri": "/DeleteSamplingRule"}, + "GetEncryptionConfig": {"method": "POST", "requestUri": "/EncryptionConfig"}, + "GetGroup": {"method": "POST", "requestUri": "/GetGroup"}, + "GetGroups": {"method": "POST", "requestUri": "/Groups"}, + "GetIndexingRules": {"method": "POST", "requestUri": "/GetIndexingRules"}, + "GetInsight": {"method": "POST", "requestUri": "/Insight"}, + "GetInsightEvents": {"method": "POST", "requestUri": "/InsightEvents"}, + "GetInsightImpactGraph": {"method": "POST", "requestUri": "/InsightImpactGraph"}, + "GetInsightSummaries": {"method": "POST", "requestUri": "/InsightSummaries"}, + "GetRetrievedTracesGraph": {"method": "POST", "requestUri": "/GetRetrievedTracesGraph"}, + "GetSamplingRules": {"method": "POST", "requestUri": "/GetSamplingRules"}, + "GetSamplingStatisticSummaries": {"method": "POST", "requestUri": "/SamplingStatisticSummaries"}, + "GetSamplingTargets": {"method": "POST", "requestUri": "/SamplingTargets"}, + "GetServiceGraph": {"method": "POST", "requestUri": "/ServiceGraph"}, + "GetTimeSeriesServiceStatistics": {"method": "POST", "requestUri": "/TimeSeriesServiceStatistics"}, + "GetTraceGraph": {"method": "POST", "requestUri": "/TraceGraph"}, + "GetTraceSegmentDestination": {"method": "POST", "requestUri": "/GetTraceSegmentDestination"}, + "GetTraceSummaries": {"method": "POST", "requestUri": "/TraceSummaries"}, + "ListResourcePolicies": {"method": "POST", "requestUri": "/ListResourcePolicies"}, + "ListRetrievedTraces": {"method": "POST", "requestUri": "/ListRetrievedTraces"}, + "ListTagsForResource": {"method": "POST", "requestUri": "/ListTagsForResource"}, + "PutEncryptionConfig": {"method": "POST", "requestUri": "/PutEncryptionConfig"}, + "PutResourcePolicy": {"method": "POST", "requestUri": "/PutResourcePolicy"}, + "PutTelemetryRecords": {"method": "POST", "requestUri": "/TelemetryRecords"}, + "PutTraceSegments": {"method": "POST", "requestUri": "/TraceSegments"}, + "StartTraceRetrieval": {"method": "POST", "requestUri": "/StartTraceRetrieval"}, + "TagResource": {"method": "POST", "requestUri": "/TagResource"}, + "UntagResource": {"method": "POST", "requestUri": "/UntagResource"}, + "UpdateGroup": {"method": "POST", "requestUri": "/UpdateGroup"}, + "UpdateIndexingRule": {"method": "POST", "requestUri": "/UpdateIndexingRule"}, + "UpdateSamplingRule": {"method": "POST", "requestUri": "/UpdateSamplingRule"}, + "UpdateTraceSegmentDestination": {"method": "POST", "requestUri": "/UpdateTraceSegmentDestination"} } } } diff --git a/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java index af7f8b9d45..e1b5946f98 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java @@ -708,6 +708,49 @@ class IamRestRouteEnforcementIntegrationTest { as(user, region, "guardduty").get("/detector").then().statusCode(200); } + /** + * A GuardDuty malware protection plan request, which GuardDutyRouteFilter moves onto {@code /_guardduty}, is + * checked as the model's route for it, on the plan its path names, and so is one sent to {@code /_guardduty} + * itself: a caller with no grant is refused before a plan is created, a grant scoped to the plan lets + * {@code GetMalwareProtectionPlan} read it and refuses another, and a deny on the plan keeps it from being + * deleted under an allow on everything. + */ + @Test + void aGuardDutyMalwareProtectionPlanRequestIsCheckedOnThePlanItsPathNames() { + String user = user("route-plan"); + String region = "eu-west-3"; + String plan = "{\"role\":\"arn:aws:iam::" + ACCOUNT + ":role/malware-scan\"," + + "\"protectedResource\":{\"s3Bucket\":{\"bucketName\":\"route-plan-" + suffix() + "\"}}}"; + refused(as(user, region, "guardduty").body(plan).post("/malware-protection-plan").then(), + "guardduty:CreateMalwareProtectionPlan"); + refused(as(user, region, "guardduty").get("/malware-protection-plan").then(), + "guardduty:ListMalwareProtectionPlans"); + // GuardDuty refuses a second plan for one bucket, so this create also shows the refused one made none. + String id = given().header("Authorization", auth(ADMIN, region, "guardduty")) + .contentType("application/json").body(plan).post("/malware-protection-plan") + .then().statusCode(200).extract().path("malwareProtectionPlanId"); + cleanup.register(() -> given().header("Authorization", auth(ADMIN, region, "guardduty")) + .delete("/malware-protection-plan/" + id)); + String arn = "arn:aws:guardduty:" + region + ":" + ACCOUNT + ":malware-protection-plan/" + id; + refused(as(user, region, "guardduty").get("/malware-protection-plan/" + id).then(), + "guardduty:GetMalwareProtectionPlan"); + refused(as(user, region, "guardduty").get("/_guardduty/malware-protection-plan/" + id).then(), + "guardduty:GetMalwareProtectionPlan"); + + policy(user, allow("guardduty:GetMalwareProtectionPlan", arn)); + as(user, region, "guardduty").get("/malware-protection-plan/" + id).then().statusCode(200) + .body("arn", equalTo(arn)); + as(user, region, "guardduty").get("/_guardduty/malware-protection-plan/" + id).then().statusCode(200) + .body("arn", equalTo(arn)); + refused(as(user, region, "guardduty").get("/malware-protection-plan/other" + id).then(), + "guardduty:GetMalwareProtectionPlan"); + + policy(user, allow("guardduty:*", "*") + "," + deny("guardduty:DeleteMalwareProtectionPlan", arn)); + refused(as(user, region, "guardduty").delete("/malware-protection-plan/" + id).then(), + "guardduty:DeleteMalwareProtectionPlan"); + as(user, region, "guardduty").get("/malware-protection-plan/" + id).then().statusCode(200); + } + /** * A segment ending in a matrix parameter, which the router ignores, is checked as the route it reaches, on the * resource its path names: the routed path carries no matrix parameter, so the rule matches and the ARN is the 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 f32b918d22..a379460a7f 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRestRoutesTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRestRoutesTest.java @@ -161,6 +161,22 @@ class IamRestRoutesTest { assertEquals(Optional.of("GetRoot"), get("/")); } + /** + * A path a route filter moved under an internal prefix, given without it, was matched decoded, so a label's value + * may hold the slashes its encoding hid: when the path matches no route with each label taking one segment, its + * labels take the segments their values span. A route that matches with one segment a label still wins, and an + * ordinary path's labels never span. + */ + @Test + void aPathMovedUnderAPrefixMayHoldTheSlashesItsLabelsWereDecodedTo() { + assertEquals(Optional.of("GetThing"), routes.operation("svc", "GET", "/things/web/part", null, true)); + assertEquals(Optional.empty(), routes.operation("svc", "GET", "/things/web/part", null, false)); + assertEquals(Map.of("ThingName", "a/b", "PartPath", "c"), + routes.match("svc", "GET", "/things/a/b/parts/c", null, true) + .map(IamRestRoutes.Match::labels).orElse(Map.of())); + assertEquals(Optional.of("ListParts"), routes.operation("svc", "GET", "/things/web/parts/list", null, true)); + } + /** * A literal segment matches itself alone, a dot in it no other character, and may end in a matrix parameter, * which RESTEasy keeps in the path it matched. diff --git a/src/test/java/io/floci/aws/services/iam/PaymentCryptographyDataPlaneIamRouteTest.java b/src/test/java/io/floci/aws/services/iam/PaymentCryptographyDataPlaneIamRouteTest.java index 2eba5b20fd..2dc7589cb6 100644 --- a/src/test/java/io/floci/aws/services/iam/PaymentCryptographyDataPlaneIamRouteTest.java +++ b/src/test/java/io/floci/aws/services/iam/PaymentCryptographyDataPlaneIamRouteTest.java @@ -1,5 +1,6 @@ package io.floci.aws.services.iam; +import io.floci.aws.core.common.SignedServiceRoute; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.core.UriInfo; import org.junit.jupiter.api.Test; @@ -16,10 +17,10 @@ import static org.mockito.Mockito.when; * *

The key of a data-plane request may be named by its identifier or by its ARN, and an ARN * carries a slash that a client sends encoded. The router rewrites the request onto the - * internal prefix, and the IAM rules are matched on the rewritten path, which is decoded. So - * the ARN arrives as a path that holds a real slash, and a rule that stops at the first slash - * would not match it: the request would resolve to no action, and a policy that denies the - * action would not be enforced. + * internal prefix, and the vendored routes, at the model's paths, are matched on the rewritten + * path without it, which is decoded. So the ARN arrives as a path that holds a real slash, and + * a route whose label stops at the first slash would not match it: the request would resolve to + * no action, and a policy that denies the action would not be enforced. * *

The rest of the repository holds a request to its standard: a request is refused however * it is sent. This is that standard for the data plane. @@ -122,6 +123,8 @@ class PaymentCryptographyDataPlaneIamRouteTest { when(uriInfo.getBaseUri()).thenReturn(URI.create("http://localhost:4566/")); when(ctx.getUriInfo()).thenReturn(uriInfo); when(ctx.getMethod()).thenReturn("POST"); + // The data plane's route filter records the prefix it moves the request under. + when(ctx.getProperty(SignedServiceRoute.INTERNAL_PREFIX_PROPERTY)).thenReturn("/_paymentcryptography"); return registry.resolveRoute(scope, ctx); } } diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDataPlaneRouteFilterTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDataPlaneRouteFilterTest.java index 4e1b2dac3b..658394251c 100644 --- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDataPlaneRouteFilterTest.java +++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDataPlaneRouteFilterTest.java @@ -59,12 +59,11 @@ class PaymentCryptographyDataPlaneRouteFilterTest { Set prefixes = new LinkedHashSet<>(); routes.fields().forEachRemaining(entry -> { String uri = entry.getValue().path("requestUri").asText(); - // The route is the model's path under the internal prefix. - assertTrue(uri.startsWith(PaymentCryptographyDataPlaneRouteFilter.INTERNAL_PREFIX), - "the route " + uri + " does not sit under the internal prefix"); - String rest = uri.substring(PaymentCryptographyDataPlaneRouteFilter.INTERNAL_PREFIX.length()); - assertTrue(rest.startsWith("/"), "the route " + uri + " names no path"); - rest = rest.substring(1); + // The route is the model's path: IAM matches a moved request on its path without the prefix. + assertTrue(!uri.startsWith(PaymentCryptographyDataPlaneRouteFilter.INTERNAL_PREFIX), + "the route " + uri + " sits under the internal prefix, not at the model's path"); + assertTrue(uri.startsWith("/"), "the route " + uri + " names no path"); + String rest = uri.substring(1); int slash = rest.indexOf('/'); assertTrue(slash > 0, "the route " + uri + " names no path"); prefixes.add("/" + rest.substring(0, slash)); diff --git a/tools/aws/regen_rest_routes.py b/tools/aws/regen_rest_routes.py index 85a8e53d8e..0b7301c1eb 100644 --- a/tools/aws/regen_rest_routes.py +++ b/tools/aws/regen_rest_routes.py @@ -79,27 +79,10 @@ MODELS: dict[str, str] = { "xray": "xray", } -# The models whose routes are rewritten onto an internal prefix, and the prefix they are rewritten -# onto, with whether the labels in their paths hold an ARN. A service whose routes sit under such a -# prefix has them there, and the prefix names them. -INTERNAL_ROUTES: dict[str, tuple[str, bool]] = { - # The Payment Cryptography data plane's routes sit under the prefix its route filter rewrites - # them onto, and the key they name is an ARN, whose slashes the rewritten path holds: the label - # spans them, as the controller's own path does. - "payment-cryptography-data": ("/_paymentcryptography", True), - # Signer's routes collide with S3's path-style ones and are rewritten onto the prefix its route - # filter owns, so its routes are vendored as the rewritten path: the action and the request's - # resource labels both resolve from it. - "signer": ("/_signer", False), - # X-Ray's routes collide with S3's path-style ones too, for the same reason and with the same - # fix: the vendored route is the path its filter rewrites the request onto. - "xray": ("/_xray", False), -} - -# Operations a model does not serve itself, so their path is not rewritten onto its internal prefix. -# The shared tags controller serves /tags/{resourceArn} for every service that is a TagHandler, and -# the service's route filter leaves that path alone; prefixing it here would advertise a route no -# request ever arrives on, and the IAM check would find no rule for it. +# Operations a model does not serve itself. The shared tags controller serves /tags/{resourceArn} for every +# service that is a TagHandler, the ARN taking the rest of the path, and the bare /tags too. A route a service's +# filter moves under an internal prefix is vendored at the model's own path all the same: IAM matches it on the +# path without the prefix the filter records (SignedServiceRoute). SHARED_ROUTES: dict[str, frozenset[str]] = { "controltower": frozenset({"TagResource", "UntagResource", "ListTagsForResource"}), "signer": frozenset({"TagResource", "UntagResource", "ListTagsForResource"}), @@ -131,22 +114,15 @@ def build(models: dict[str, dict], provenance: str) -> dict: model = models[name] if model["metadata"].get("protocol") not in ("rest-json", "rest-xml"): raise SystemExit(f"error: {name} is not a REST model") - prefix, arn_labels = INTERNAL_ROUTES.get(name, ("", False)) shared = SHARED_ROUTES.get(name, frozenset()) operations = {} for operation in sorted(model["operations"]): http = model["operations"][operation]["http"] + request_uri = http["requestUri"] if operation in shared: - request_uri = http["requestUri"] # A shared tags route names its resource as an ARN, which holds slashes: the label # has to span them or the route matches no tag request at all. request_uri = re.sub(r"\{([^}]*[Aa]rn[^}]*)}", r"{\1+}", request_uri) - else: - request_uri = prefix + http["requestUri"] - if arn_labels: - # A label holding an ARN spans the slashes the ARN holds, which the rewritten path - # holds as they are. - request_uri = re.sub(r"\{([^}]+)\}", r"{\1+}", request_uri) route = {"method": http["method"], "requestUri": request_uri} if operation in shared: # SharedTagsController also serves the bare path, reading POST's body and diff --git a/tools/aws/test_regen_rest_routes.py b/tools/aws/test_regen_rest_routes.py index fbfd328df8..28df3f4be6 100644 --- a/tools/aws/test_regen_rest_routes.py +++ b/tools/aws/test_regen_rest_routes.py @@ -145,3 +145,10 @@ def test_shared_tag_alternative_collision_is_rejected(): with pytest.raises(SystemExit, match="one route names more than one operation"): r.build({"controltower": model("rest-json", "2020-01-01", TagResource=("POST", "/tags/{resourceArn}"), OtherOperation=("POST", "/tags"))}, "test") + + +@pytest.mark.parametrize("name", ["payment-cryptography-data", "signer", "xray", "guardduty"]) +def test_a_model_a_route_filter_moves_under_a_prefix_keeps_its_own_paths(name): + # IAM matches a moved request on its path without the prefix its filter records, so the routes are the model's. + doc = r.build({name: model("rest-json", "2020-01-01", GetThing=("GET", "/things/{ThingId}"))}, "test") + assert doc["models"][name]["operations"]["GetThing"]["requestUri"] == "/things/{ThingId}"