mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(iam): check the API Gateway and Lambda routes the action map names, and test them (#6036)
Under IAM enforcement a REST request is checked as the action its route maps to, and a route no rule maps is let through unchecked. On #5604 the S3 and API Gateway entries of iam-authorized-actions.json were noted as never read, since those requests are authorized by route, with a test comparing them with the route table asked for. This adds that test, against each operation's real route, and fixes what it found. - IamRestRouteCoverageTest builds a request on each operation's route, as botocore's model gives it, and checks that the registry resolves every S3, API Gateway and Lambda entry of iam-authorized-actions.json to the action the entry names. The routes are vendored, one operation to a line, in src/test/resources/aws/rest-routes.json by the new tools/aws/regen_rest_routes.py, which make aws-data-sync and aws-data-check now run. - API Gateway: only /account and /restapis were mapped, so API keys, usage plans, client certificates, base path mappings, domain names and all of the v2 API went unchecked. The management API is now checked as apigateway:<method> on any route, as AWS authorizes it, and RejectDomainNameAccessAssociation and PutRoutingRule as their own actions. The v2 operations AWS checks only as actions of their own names, routing rules and portals, are not served by Floci. - Lambda: InvokeWithResponseStream went unchecked; it is now checked as lambda:InvokeFunction, against the qualified function as an invoke is. GetLayerVersionByArn is checked as lambda:GetLayerVersion. It shares its path with ListLayers, so a rule can now require a query parameter. - S3: the two bucket metadata configuration entries are not applied. Floci serves no metadata configuration, and such a request falls through to ListObjects or DeleteBucket, so it stays checked as the operation that runs.
This commit is contained in:
1 parent
39a164cd19
commit
24a960a599
11 files changed
+971
-15
No files matched your search
@@ -241,6 +241,20 @@ class IamActionRegistryTest {
|
||||
assertEquals("lambda:InvokeFunction", registry.resolveRoute("lambda", invoke));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRuleNamingAQueryParameterMatchesOnlyARequestCarryingItWithItsValue() {
|
||||
// GET /layers?find=LayerVersion is GetLayerVersionByArn, while GET /layers is ListLayers.
|
||||
MultivaluedHashMap<String, String> byArn = new MultivaluedHashMap<>();
|
||||
byArn.putSingle("find", "LayerVersion");
|
||||
assertEquals("lambda:GetLayerVersion", registry.resolveRoute("lambda",
|
||||
mockCtx("GET", "/2018-10-31/layers", byArn, MediaType.APPLICATION_JSON_TYPE, "{}")));
|
||||
MultivaluedHashMap<String, String> other = new MultivaluedHashMap<>();
|
||||
other.putSingle("find", "Layer");
|
||||
assertNull(registry.resolveRoute("lambda",
|
||||
mockCtx("GET", "/2018-10-31/layers", other, MediaType.APPLICATION_JSON_TYPE, "{}")));
|
||||
assertNull(lambdaAction("GET", "/2018-10-31/layers"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void durableExecutionRoutesResolveToTheirActions() {
|
||||
String arn = "arn%3Aaws%3Alambda%3Aus-east-1%3A000000000000%3Afunction%3Af%3A%24LATEST"
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.junit.jupiter.api.DynamicTest;
|
||||
import org.junit.jupiter.api.TestFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* A REST request is authorized by its route, so an operation is checked as the IAM action AWS checks
|
||||
* for it only if a rule in {@link IamActionRegistry} maps its route to that action. This builds a
|
||||
* request on each operation's route, as botocore's model gives it ({@code rest-routes.json}, from
|
||||
* {@code tools/aws/regen_rest_routes.py}), and compares the action the registry resolves with the one
|
||||
* {@code iam-authorized-actions.json} names for the operation, or else the operation's own name.
|
||||
*/
|
||||
class IamRestRouteCoverageTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final Pattern LABEL = Pattern.compile("\\{([^}+]+)(\\+?)}");
|
||||
|
||||
/** The REST namespaces whose entries in {@code iam-authorized-actions.json} only the route table can apply. */
|
||||
private static final Set<String> ROUTED_NAMESPACES = Set.of("s3", "apigateway", "lambda");
|
||||
|
||||
/**
|
||||
* Operations Floci does not serve, whose request runs as another operation instead and so is checked
|
||||
* as that one: S3 has no bucket metadata configuration, and {@code ?metadataConfiguration} on a
|
||||
* bucket falls through to ListObjects and DeleteBucket. Checking it as the metadata table action
|
||||
* would let that action list or delete the bucket.
|
||||
*/
|
||||
private static final Map<String, String> RUN_AS_ANOTHER_OPERATION = Map.of(
|
||||
"GetBucketMetadataConfiguration", "s3:ListBucket",
|
||||
"DeleteBucketMetadataConfiguration", "s3:DeleteBucket");
|
||||
|
||||
private final IamActionRegistry registry = new IamActionRegistry();
|
||||
|
||||
@TestFactory
|
||||
Stream<DynamicTest> eachVendoredActionOfARestServiceIsWhatItsRouteResolvesTo() throws IOException {
|
||||
JsonNode models = load("/aws/rest-routes.json").path("models");
|
||||
JsonNode authorized = load("/aws/iam-authorized-actions.json").path("authorizedActions");
|
||||
List<DynamicTest> tests = new ArrayList<>();
|
||||
for (String namespace : ROUTED_NAMESPACES) {
|
||||
Iterator<Map.Entry<String, JsonNode>> entries = authorized.path(namespace).fields();
|
||||
while (entries.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = entries.next();
|
||||
List<Route> routes = routesOf(models, namespace, entry.getKey());
|
||||
String expected = RUN_AS_ANOTHER_OPERATION.getOrDefault(entry.getKey(), entry.getValue().asText());
|
||||
tests.add(DynamicTest.dynamicTest(namespace + " " + entry.getKey(), () -> {
|
||||
assertFalse(routes.isEmpty(), "no model route for " + entry.getKey());
|
||||
for (Route route : routes) {
|
||||
assertEquals(expected, resolve(route), route.toString());
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
return tests.stream();
|
||||
}
|
||||
|
||||
/** Every model route of {@code operation} among the models Floci authorizes under {@code scope}. */
|
||||
private static List<Route> routesOf(JsonNode models, String scope, String operation) {
|
||||
List<Route> routes = new ArrayList<>();
|
||||
Iterator<Map.Entry<String, JsonNode>> all = models.fields();
|
||||
while (all.hasNext()) {
|
||||
Map.Entry<String, JsonNode> model = all.next();
|
||||
JsonNode route = model.getValue().path("operations").path(operation);
|
||||
if (scope.equals(model.getValue().path("credentialScope").asText()) && !route.isMissingNode()) {
|
||||
routes.add(new Route(scope, model.getKey(), operation, route.path("method").asText(),
|
||||
route.path("requestUri").asText()));
|
||||
}
|
||||
}
|
||||
return routes;
|
||||
}
|
||||
|
||||
private String resolve(Route route) {
|
||||
return registry.resolveRoute(route.scope(), route.request());
|
||||
}
|
||||
|
||||
private static JsonNode load(String resource) throws IOException {
|
||||
try (InputStream in = IamRestRouteCoverageTest.class.getResourceAsStream(resource)) {
|
||||
return MAPPER.readTree(in);
|
||||
}
|
||||
}
|
||||
|
||||
/** An operation's route: its method, and its request URI with each label filled in. */
|
||||
private record Route(String scope, String model, String operation, String method, String requestUri) {
|
||||
|
||||
ContainerRequestContext request() {
|
||||
int question = requestUri.indexOf('?');
|
||||
String path = fill(question < 0 ? requestUri : requestUri.substring(0, question));
|
||||
MultivaluedMap<String, String> query = new MultivaluedHashMap<>();
|
||||
if (question >= 0) {
|
||||
for (String parameter : requestUri.substring(question + 1).split("&")) {
|
||||
int equals = parameter.indexOf('=');
|
||||
query.add(equals < 0 ? parameter : parameter.substring(0, equals),
|
||||
equals < 0 ? "" : parameter.substring(equals + 1));
|
||||
}
|
||||
}
|
||||
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
|
||||
UriInfo uriInfo = mock(UriInfo.class);
|
||||
when(uriInfo.getQueryParameters()).thenReturn(query);
|
||||
when(uriInfo.getPath()).thenReturn(path);
|
||||
when(uriInfo.getRequestUri()).thenReturn(URI.create("http://localhost:4566" + path));
|
||||
when(uriInfo.getBaseUri()).thenReturn(URI.create("http://localhost:4566/"));
|
||||
when(ctx.getUriInfo()).thenReturn(uriInfo);
|
||||
when(ctx.getMethod()).thenReturn(method);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
/** The path with each {@code {label}} filled in, and a greedy {@code {label+}} given two segments. */
|
||||
private static String fill(String template) {
|
||||
Matcher label = LABEL.matcher(template);
|
||||
StringBuilder path = new StringBuilder();
|
||||
while (label.find()) {
|
||||
String value = label.group(1).toLowerCase() + "-value";
|
||||
label.appendReplacement(path, label.group(2).isEmpty() ? value : value + "/part");
|
||||
}
|
||||
label.appendTail(path);
|
||||
return path.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return model + " " + operation + ": " + method + " " + requestUri;
|
||||
}
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
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 io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
/**
|
||||
* REST requests whose route no rule mapped to an IAM action were let through under enforcement
|
||||
* unchecked. These routes are mapped now, and a caller needs the action AWS checks for them.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class IamRestRouteEnforcementIntegrationTest {
|
||||
|
||||
private static final String ADMIN = "test";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
|
||||
@TestHTTPResource("/")
|
||||
static URI baseUri;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
/** Each user's access key ID, by user name. */
|
||||
private final Map<String, String> keys = new HashMap<>();
|
||||
|
||||
@Test
|
||||
void apiGatewayManagementRoutesBeyondRestApisAreCheckedByMethod() {
|
||||
String user = user("route-apigateway");
|
||||
String plan = "{\"name\":\"route-plan-" + suffix() + "\"}";
|
||||
|
||||
policy(user, allow("apigateway:GET", "*"));
|
||||
refused(as(user, "apigateway").body(plan).post("/usageplans").then(), "apigateway:POST");
|
||||
as(user, "apigateway").get("/usageplans").then().statusCode(200);
|
||||
|
||||
policy(user, allow("apigateway:POST", "*"));
|
||||
String id = as(user, "apigateway").body(plan).post("/usageplans").then().statusCode(201).extract().path("id");
|
||||
cleanup.register(() -> given().header("Authorization", auth(ADMIN, "apigateway")).delete("/usageplans/" + id));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getLayerVersionByArnIsCheckedAsGetLayerVersion() {
|
||||
String user = user("route-layer");
|
||||
String arn = "arn:aws:lambda:us-east-1:" + ACCOUNT + ":layer:route-layer-" + suffix() + ":1";
|
||||
|
||||
policy(user, allow("lambda:ListLayers", "*"));
|
||||
refused(as(user, "lambda").queryParam("find", "LayerVersion").queryParam("Arn", arn)
|
||||
.get("/2018-10-31/layers").then(), "lambda:GetLayerVersion");
|
||||
policy(user, allow("lambda:GetLayerVersion", "*"));
|
||||
// Allowed, the request reaches Lambda, which has no such layer.
|
||||
as(user, "lambda").queryParam("find", "LayerVersion").queryParam("Arn", arn)
|
||||
.get("/2018-10-31/layers").then().statusCode(404);
|
||||
}
|
||||
|
||||
private static void refused(ValidatableResponse response, String action) {
|
||||
response.statusCode(403).body(containsString(action)).body(not(containsString("iam:PassRole")));
|
||||
}
|
||||
|
||||
private static String allow(String action, String resource) {
|
||||
return "{\"Effect\":\"Allow\",\"Action\":\"" + action + "\",\"Resource\":\"" + resource + "\"}";
|
||||
}
|
||||
|
||||
private void policy(String user, String statements) {
|
||||
EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ADMIN, "iam"), user, "p",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
|
||||
}
|
||||
|
||||
/** Creates a user, removed afterwards, and returns its access key ID under the user's name. */
|
||||
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 RequestSpecification as(String user, String service) {
|
||||
return given().header("Authorization", auth(keys.get(user), service)).contentType("application/json");
|
||||
}
|
||||
|
||||
private static String suffix() {
|
||||
return Long.toString(System.nanoTime(), 36);
|
||||
}
|
||||
}
|
||||
@@ -1179,6 +1179,15 @@ class ResourceArnBuilderTest {
|
||||
assertEquals("*", builder.build("lambda", ctx, "us-east-1", "000000000000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStreamingInvokeResolvesItsQualifiedFunctionAsAnInvokeDoes() {
|
||||
// A streaming invoke is an invoke: its qualifier and the account its function ARN names count.
|
||||
when(uriInfo.getPath()).thenReturn("/2021-11-15/functions/my-function/response-streaming-invocations");
|
||||
queryParams.putSingle("Qualifier", "prod");
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function:prod",
|
||||
builder.build("lambda", ctx, "us-east-1", "000000000000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lambdaRoutesOtherThanInvokeAreCheckedAgainstTheCallersUnqualifiedFunction() {
|
||||
when(uriInfo.getPath()).thenReturn(
|
||||
|
||||
Reference in new issue
Block a user