diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java index 3bd2e2f971..31d76e4b46 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamActionRegistry.java @@ -16,7 +16,11 @@ import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.UriInfo; import org.jboss.logging.Logger; +import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext; +import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveContainerRequestContext; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.regex.Pattern; @@ -586,7 +590,7 @@ public class IamActionRegistry { return false; } String method = ctx.getMethod().toUpperCase(); - String path = rawPath(ctx.getUriInfo()); + String path = sentPath(ctx.getUriInfo()); for (ActionRule rule : RULES) { if (rule.beforeS3QueryOverrides() && rule.matches(credentialScope, method, path, ctx)) { return true; @@ -670,7 +674,7 @@ public class IamActionRegistry { String method = ctx.getMethod().toUpperCase(); // An S3 key may end in a slash, PUT /bucket// writes the key "/", and S3's rules already take a // bucket's one trailing slash, so an S3 path is matched as sent. - String path = "s3".equals(credentialScope) ? rawPath(ctx.getUriInfo()) : routedPath(ctx.getUriInfo()); + String path = "s3".equals(credentialScope) ? sentPath(ctx.getUriInfo()) : routedPath(ctx); if ("s3".equals(credentialScope)) { // An S3 Control route is matched before the query overrides below, which would read the @@ -702,16 +706,51 @@ public class IamActionRegistry { return null; } + /** + * The path the router matched, relative to the application root. A request no filter rewrote is matched + * on its normalized path, still percent-encoded but with encoded unreserved characters such as {@code %2E} + * decoded and dot segments removed, so {@code /functions/x/%2E%2E/fn} is {@code /functions/fn}; a request + * a filter rewrote is matched on its new path, decoded. {@link #sentPath} for a synthetic context. + */ + static String rawPath(ContainerRequestContext ctx) { + ResteasyReactiveRequestContext request = routingContext(ctx); + return request == null ? sentPath(ctx.getUriInfo()) : rooted(request.getPathWithoutPrefix()); + } + /** * The request path relative to the application root, as {@link UriInfo#getPath()} gives it, but * still percent-encoded. */ - static String rawPath(UriInfo uriInfo) { + static String sentPath(UriInfo uriInfo) { String path = uriInfo.getRequestUri().getRawPath(); String base = uriInfo.getBaseUri().getRawPath(); if (base != null && base.length() > 1 && path.startsWith(base)) { path = path.substring(base.length() - 1); } + return rooted(path); + } + + /** + * {@link #rawPath} decoded: the path {@link UriInfo#getPath()} would give for the route the router + * matched. {@link UriInfo#getPath()} itself for a synthetic context. + */ + public static String decodedPath(ContainerRequestContext ctx) { + ResteasyReactiveRequestContext request = routingContext(ctx); + if (request == null) { + return ctx.getUriInfo().getPath(); + } + String path = request.getPathWithoutPrefix(); + boolean rewritten = !request.getPath().equals(request.serverRequest().getRequestNormalisedPath()); + return rooted(rewritten ? path : URLDecoder.decode(path.replace("+", "%2B"), StandardCharsets.UTF_8)); + } + + private static ResteasyReactiveRequestContext routingContext(ContainerRequestContext ctx) { + return ctx instanceof ResteasyReactiveContainerRequestContext container + && container.getServerRequestContext() instanceof ResteasyReactiveRequestContext request + ? request : null; + } + + private static String rooted(String path) { return path.startsWith("/") ? path : "/" + path; } @@ -720,8 +759,8 @@ public class IamActionRegistry { * so a rule ending at the route's last segment has to match it too, or the request would pass as an * unknown action. */ - static String routedPath(UriInfo uriInfo) { - String path = rawPath(uriInfo); + static String routedPath(ContainerRequestContext ctx) { + String path = rawPath(ctx); while (path.length() > 1 && path.endsWith("/")) { path = path.substring(0, path.length() - 1); } diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java index ec5398f3e3..56d2c727f1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java @@ -190,7 +190,8 @@ public class ResourceArnBuilder { if (credentialScope == null) { return List.of("*"); } - String path = ctx.getUriInfo().getPath(); + String path = "s3".equals(credentialScope) ? ctx.getUriInfo().getPath() + : IamActionRegistry.decodedPath(ctx); return switch (credentialScope) { case "s3" -> buildS3Resources(operation, path, region); case "lambda" -> List.of(buildLambdaArn(path, ctx, region, accountId)); @@ -257,7 +258,7 @@ public class ResourceArnBuilder { if (body == null) { return "*"; } - String path = ctx.getUriInfo().getPath(); + String path = IamActionRegistry.decodedPath(ctx); boolean create = path.endsWith("/groups") || path.endsWith("/groups/"); String group = create ? body.path("Name").asText() : body.path("Group").asText(body.path("GroupName").asText()); @@ -1023,7 +1024,7 @@ public class ResourceArnBuilder { if (!path.startsWith(layers)) { return null; } - String raw = IamActionRegistry.rawPath(ctx.getUriInfo()); + String raw = IamActionRegistry.rawPath(ctx); if (!raw.startsWith(layers)) { return "*"; } @@ -1238,7 +1239,7 @@ public class ResourceArnBuilder { * stays escaped, so a segment cannot pass for more than one. */ private static String buildApiGatewayArn(ContainerRequestContext ctx, String region, String partition) { - String[] raw = IamActionRegistry.routedPath(ctx.getUriInfo()).split("/", -1); + String[] raw = IamActionRegistry.routedPath(ctx).split("/", -1); List segments = new ArrayList<>(); for (int i = 1; i < raw.length; i++) { String segment = pathSegment(raw[i]); @@ -1290,7 +1291,7 @@ public class ResourceArnBuilder { return slash < 0 || slash == tagged.length() - 1 ? "*" : eksClusterArn(tagged.substring(slash + 1), region, accountId); } - String[] segments = IamActionRegistry.routedPath(ctx.getUriInfo()).substring(1).split("/", -1); + String[] segments = IamActionRegistry.routedPath(ctx).substring(1).split("/", -1); if (segments.length == 1) { JsonNode body = "clusters".equals(segments[0]) && "POST".equalsIgnoreCase(ctx.getMethod()) ? readJsonBody(ctx) : null; @@ -1384,7 +1385,7 @@ public class ResourceArnBuilder { * names none. */ public String taggedArn(ContainerRequestContext ctx) { - String path = ctx.getUriInfo().getPath(); + String path = IamActionRegistry.decodedPath(ctx); for (String route : List.of("/tags", "/v1/tags")) { if (path.startsWith(route + "/")) { return path.substring(route.length() + 1); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ApiGatewayPathArnEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ApiGatewayPathArnEnforcementIntegrationTest.java index f7587858ad..1d2d571462 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/ApiGatewayPathArnEnforcementIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/ApiGatewayPathArnEnforcementIntegrationTest.java @@ -72,6 +72,7 @@ class ApiGatewayPathArnEnforcementIntegrationTest { get(user, "/restapis/x/%2E%2E/" + apiId + "/stages").statusCode(200); assertReached(getAsWritten(user, "/restapis//" + apiId + "/stages")); assertReached(getAsWritten(user, "/restapis/x/%2E%2E//" + apiId + "/stages")); + assertReached(getAsWritten(user, "/restapis/" + apiId + "//%2E%2E/stages")); policy(user, allow("apigateway:GET", "arn:aws:apigateway:*::/restapis")); refused(get(user, "/restapis/" + apiId + "/stages")); @@ -83,6 +84,7 @@ class ApiGatewayPathArnEnforcementIntegrationTest { refused(get(user, "/restapis/x/%2E%2E/" + apiId + "/stages")); assertRefused(getAsWritten(user, "/restapis//" + apiId + "/stages")); assertRefused(getAsWritten(user, "/restapis/x/%2E%2E//" + apiId + "/stages")); + assertRefused(getAsWritten(user, "/restapis/" + apiId + "//%2E%2E/stages")); get(user, "/restapis").statusCode(200); } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/RoutedPathIamEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/RoutedPathIamEnforcementIntegrationTest.java new file mode 100644 index 0000000000..df04f5d22d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/RoutedPathIamEnforcementIntegrationTest.java @@ -0,0 +1,101 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.testing.EnforcementFixtures; +import io.github.hectorvent.floci.testing.IamEnforcementProfile; +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * A REST request is authorized as the route the router matched, whose path has its encoded dot segments + * resolved, so a path written with {@code %2E%2E} is checked as the operation and resource it reaches. + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class RoutedPathIamEnforcementIntegrationTest { + + private static final String ADMIN = "test"; + + @TestHTTPResource("/") + URI baseUri; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + /** Each user's access key ID, by user name. */ + private final Map keys = new HashMap<>(); + + @Test + void aLambdaPathWithADotSegmentIsCheckedAsTheFunctionItReaches() throws Exception { + String function = "routed-" + suffix(); + String user = user("routed-lambda"); + policy(user, allow("lambda:*", "*") + "," + + deny("lambda:GetFunction", "arn:aws:lambda:*:*:function:" + function)); + + for (String path : List.of( + "/2015-03-31/functions/" + function, + "/2015-03-31/functions/x/%2E%2E/" + function, + "/2015-03-31/functions/" + function + "/x/%2E%2E", + "/2015-03-31/functions/x//%2E%2E/%2E%2E/" + function)) { + HttpResponse response = get(user, "lambda", path); + assertEquals(403, response.statusCode(), path + ": " + response.body()); + assertThat(response.body(), containsString("lambda:GetFunction")); + } + + HttpResponse other = get(user, "lambda", "/2015-03-31/functions/x/%2E%2E/other-" + function); + assertEquals(404, other.statusCode(), other.body()); + assertThat(other.body(), containsString("Function not found: other-" + function)); + } + + /** Sends {@code path} as written: RestAssured and the AWS SDKs resolve its dot and empty segments first. */ + private HttpResponse get(String user, String service, String path) throws Exception { + URI uri = URI.create(baseUri.getScheme() + "://" + baseUri.getRawAuthority() + path); + try (HttpClient client = HttpClient.newHttpClient()) { + return client.send(HttpRequest.newBuilder(uri) + .header("Authorization", auth(keys.get(user), service)).GET().build(), + HttpResponse.BodyHandlers.ofString()); + } + } + + private static String allow(String action, String resource) { + return "{\"Effect\":\"Allow\",\"Action\":\"" + action + "\",\"Resource\":\"" + resource + "\"}"; + } + + private static String deny(String action, String resource) { + return "{\"Effect\":\"Deny\",\"Action\":\"" + action + "\",\"Resource\":\"" + resource + "\"}"; + } + + /** Replaces the user's one inline policy. */ + private void policy(String user, String statements) { + EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ADMIN, "iam"), user, "p", + "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}"); + } + + private String user(String name) { + String userName = name + "-" + suffix(); + String accessKeyId = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ADMIN, "iam"), userName) + .accessKeyId(); + keys.put(userName, accessKeyId); + return userName; + } + + private static String suffix() { + return Long.toString(System.nanoTime(), 36); + } +}