fix(iam): match requests moved under an internal prefix on their model's routes (#8067)

This commit is contained in:
mrfelek authored and GitHub committed 2026-11-12 07:40:00 -04:00
1 parent 94ba685306
commit f6b95fda16
10 files changed
+248 -126

No files matched your search

@@ -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.
*
* <p>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<String> 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<String> 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) {
@@ -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<String> operation = restRoutes.operation(credentialScope, method, path,
ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters());
Optional<String> 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;
@@ -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.
*
* <p>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.
*
* <p>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<String> labels, int[] ranks, Map<String, String> query,
Map<String, String> located) {
private record Route(String operation, Pattern path, Pattern spanning, List<String> labels, int[] ranks,
Map<String, String> query, Map<String, String> located) {
boolean matches(String requestPath, MultivaluedMap<String, String> 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<String, String> parameters, boolean spanned) {
if (!pattern(spanned).matcher(requestPath).matches()) {
return false;
}
for (Map.Entry<String, String> 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<String, String> labelValues(String requestPath) {
Matcher matcher = path.matcher(requestPath);
Map<String, String> 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<String> operation(String scope, String method, String path, MultivaluedMap<String, String> 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> match(String scope, String method, String path, MultivaluedMap<String, String> query) {
return match(scope, method, path, query, false);
}
/** As {@link #operation(String, String, String, MultivaluedMap, boolean)}, with the label values. */
Optional<Match> match(String scope, String method, String path, MultivaluedMap<String, String> query,
boolean movedUnderPrefix) {
String requestPath = IamActionRegistry.withoutTrailingSlash(path);
Optional<Match> match = best(scope, method, requestPath, query, false);
return match.isPresent() || !movedUnderPrefix ? match : best(scope, method, requestPath, query, true);
}
private Optional<Match> best(String scope, String method, String requestPath, MultivaluedMap<String, String> 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<String> segments = path.equals("/") ? List.of() : List.of(path.substring(1).split("/", -1));
StringBuilder pattern = new StringBuilder();
StringBuilder spanning = new StringBuilder();
List<String> 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<String, String> 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);
}
}