mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(iam): check requests on the resources they name (#6511)
Under IAM enforcement a request is checked against the resources it acts on. ResourceArnBuilder builds their ARNs by hand for 17 namespaces; every other request was checked on *, so a grant scoped to a resource was refused and a deny scoped to one never applied. AWS's Service Reference lists the resource types each action acts on and each type's ARN formats, but not which request member names a resource; botocore's models give the members. A new generator, tools/aws/regen_iam_request_resources.py, joins the two into src/main/resources/aws/iam-request-resources.json: for each operation, the action it is checked as, that action's resource types and the resources its request names, by a member holding a resource's ARN or by members filling the variables of a type's format, matched by name. A variable nothing fills is left open, as a service mints a new resource's id; a type nothing names is not checked, as an action lists the optional resources its requests may use; and types named only through the same members are alternatives, of which the one named in full is kept. Corrections give a v2 CreateLoadBalancer the load balancer of its Type, application when it gives none (a Type outside application, network and gateway is now refused, as AWS refuses it, rather than read as an application load balancer the table does not name), and read StartExecution's and StartSyncExecution's stateMachineArn up to a #, as Floci runs the machine before Step Functions Local's test case. A state machine's version or alias, stateMachine:<name>:<qualifier>, is checked on the state machine's ARN, as Step Functions authorizes it, so an execution started through one is the state machine's too. RequestResources reads them from a JSON or CBOR body or a Query form, for the namespaces the table reads, and ResourceArnBuilder uses them where it has no branch. They are read for the operation the request is dispatched as, which IamEnforcementFilter resolves and checks the action of (the Query action, the JSON target or the Smithy RPC v2 path's operation), never for an X-Amz-Target or Action the request names again, and as the handlers read them: a list only from a list, a number or a null as its text. A member whose botocore shape is an account id gives the account of the types named by variables: ECR's registryId selects the registry its handler acts in, and a JSON null is no registry, the caller's, as ECR reads it. ECR's BatchGetRepositoryScanningConfiguration, whose AWS request has no registryId, no longer reads one: it acts in the caller's registry, where IAM checks it. An ARN value counts when it matches the format of a type the action acts on; one naming another account or Region is checked as given and as each resource of that name a handler may act on instead, in its account or the caller's and its Region or the request's (ECR's tag handlers keep the ARN's account in the request's Region). A request naming none, or whose action acts on no resource type, stays on *, as AWS checks it. A create's tagging action is checked on the same resources, except where the create makes a resource under a parent its action acts on: CreateListener acts on a load balancer and CreateRule on a listener, and their tags are checked on the new listener or rule, built from the parent's ARN with the type word replaced and its own id open. The table gives these from the formats: a child type's is its parent's with one id appended. So the AWS Load Balancer Controller's policy, which allows AddTags at creation only on target groups and application and network load balancers, and on listeners and rules, now holds. The first namespaces read are Elastic Load Balancing, ECR, Step Functions and Cognito user pools (298 operations); the 99 others Floci serves are listed as not read yet, with their reason, and RequestResourceNamespacesIntegrationTest fails for a served namespace in none of the lists. make iam-request-resources-check, part of aws-data-check, re-derives every operation from the pinned botocore; make iam-request-resources-verify, part of iam-data-verify, checks the actions, types and formats against AWS, and the IAM data drift workflow also runs on a change to the table or its generator. Not in this change: the 99 other namespaces, Query lists other than Name.member.N, identifiers inside structures (SetRulePriorities, CreateStateMachineAlias' routing configuration) and EventBridge.
This commit is contained in:
1 parent
b66ee9ecf0
commit
932af22f4a
20 files changed
+3182
-48
No files matched your search
+26
-29
@@ -104,7 +104,7 @@ class IamEnforcementFilterTest {
|
||||
when(services.iam()).thenReturn(iamConfig);
|
||||
when(iamConfig.enforcementEnabled()).thenReturn(true);
|
||||
when(config.defaultRegion()).thenReturn("us-east-1");
|
||||
when(arnBuilder.buildResources(any(), any(), any(), any())).thenReturn(List.of("*"));
|
||||
when(arnBuilder.buildResources(any(), any(), any(), any(), any(), any())).thenReturn(List.of("*"));
|
||||
when(arnBuilder.build(any(), any(), any(), any())).thenReturn("*");
|
||||
// Default: scopes are already canonical. Alias handling is asserted explicitly below.
|
||||
when(catalog.canonicalCredentialScope(anyString())).thenAnswer(inv -> inv.getArgument(0));
|
||||
@@ -168,7 +168,7 @@ class IamEnforcementFilterTest {
|
||||
{"Effect":"Allow","Action":"lambda:InvokeFunction",
|
||||
"Resource":"arn:aws:lambda:us-east-1:222233334444:function:fn"}
|
||||
]}""")));
|
||||
when(arnBuilder.buildResources("lambda", containerRequest, "us-east-1", "222233334444"))
|
||||
when(arnBuilder.buildResources(eq("lambda"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws")))
|
||||
.thenReturn(List.of("arn:aws:lambda:us-east-1:222233334444:function:fn"));
|
||||
when(evaluator.evaluateResolvedResourcePolicy(
|
||||
any(),
|
||||
@@ -185,7 +185,7 @@ class IamEnforcementFilterTest {
|
||||
|
||||
filter.filter(containerRequest);
|
||||
|
||||
verify(arnBuilder).buildResources("lambda", containerRequest, "us-east-1", "222233334444");
|
||||
verify(arnBuilder).buildResources(eq("lambda"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -207,7 +207,7 @@ class IamEnforcementFilterTest {
|
||||
{"Effect":"Allow","Action":"s3:GetObject",
|
||||
"Resource":"arn:aws:s3:::mybucket/obj"}
|
||||
]}""")));
|
||||
when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
|
||||
when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws")))
|
||||
.thenReturn(List.of("arn:aws:s3:::mybucket/obj"));
|
||||
when(evaluator.evaluateResolvedResourcePolicy(
|
||||
any(),
|
||||
@@ -252,7 +252,7 @@ class IamEnforcementFilterTest {
|
||||
{"Effect":"Allow","Action":"s3:GetObject",
|
||||
"Resource":"arn:aws:s3:::mybucket/obj"}
|
||||
]}""")));
|
||||
when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
|
||||
when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws")))
|
||||
.thenReturn(List.of("arn:aws:s3:::mybucket/obj"));
|
||||
when(evaluator.evaluateResolvedResourcePolicy(
|
||||
any(),
|
||||
@@ -287,7 +287,7 @@ class IamEnforcementFilterTest {
|
||||
// Resolve for the serving service only. Left unstubbed the filter would leave through its
|
||||
// permissive unknown-action branch and the deny below would never be reached.
|
||||
when(actionRegistry.resolve("dynamodb", containerRequest)).thenReturn("dynamodb:PutItem");
|
||||
when(arnBuilder.buildResources("dynamodb", containerRequest, "us-east-1", "000000000000"))
|
||||
when(arnBuilder.buildResources(eq("dynamodb"), any(), eq(containerRequest), eq("us-east-1"), eq("000000000000"), eq("aws")))
|
||||
.thenReturn(List.of("*"));
|
||||
when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), eq("dynamodb:PutItem"), any(), any()))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.DENY);
|
||||
@@ -417,8 +417,7 @@ class IamEnforcementFilterTest {
|
||||
|
||||
verify(actionRegistry).resolveRoute("apigateway", containerRequest);
|
||||
verify(actionRegistry, never()).resolveRoute("iam", containerRequest);
|
||||
verify(arnBuilder).buildResources("apigateway", containerRequest,
|
||||
"us-east-1", "000000000000");
|
||||
verify(arnBuilder).buildResources(eq("apigateway"), any(), eq(containerRequest), eq("us-east-1"), eq("000000000000"), eq("aws"));
|
||||
verify(conditionContextResolver).resolve("apigateway", "apigateway:POST", containerRequest);
|
||||
}
|
||||
|
||||
@@ -494,8 +493,7 @@ class IamEnforcementFilterTest {
|
||||
|
||||
verify(actionRegistry).queryAction(containerRequest);
|
||||
verify(actionRegistry, never()).resolve("lambda", containerRequest);
|
||||
verify(arnBuilder).buildResources("iam", containerRequest,
|
||||
"us-east-1", "000000000000");
|
||||
verify(arnBuilder).buildResources(eq("iam"), any(), eq(containerRequest), eq("us-east-1"), eq("000000000000"), eq("aws"));
|
||||
verify(conditionContextResolver).resolve("iam", "iam:CreateUser", containerRequest);
|
||||
}
|
||||
|
||||
@@ -520,8 +518,7 @@ class IamEnforcementFilterTest {
|
||||
|
||||
verify(actionRegistry).queryAction(containerRequest);
|
||||
verify(actionRegistry, never()).resolve("lambda", containerRequest);
|
||||
verify(arnBuilder).buildResources("iam", containerRequest,
|
||||
"us-east-1", "000000000000");
|
||||
verify(arnBuilder).buildResources(eq("iam"), any(), eq(containerRequest), eq("us-east-1"), eq("000000000000"), eq("aws"));
|
||||
verify(conditionContextResolver).resolve("iam", "iam:CreateUser", containerRequest);
|
||||
}
|
||||
|
||||
@@ -1159,7 +1156,7 @@ class IamEnforcementFilterTest {
|
||||
{"Effect":"Allow","Action":"dynamodb:GetItem",
|
||||
"Resource":"arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable"}
|
||||
]}""")));
|
||||
when(arnBuilder.buildResources("dynamodb", containerRequest, "us-east-1", "000000000000"))
|
||||
when(arnBuilder.buildResources(eq("dynamodb"), any(), eq(containerRequest), eq("us-east-1"), eq("000000000000"), eq("aws")))
|
||||
.thenReturn(List.of("arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable"));
|
||||
when(evaluator.evaluateResolvedResourcePolicy(
|
||||
any(),
|
||||
@@ -1176,7 +1173,7 @@ class IamEnforcementFilterTest {
|
||||
|
||||
filter.filter(containerRequest);
|
||||
|
||||
verify(arnBuilder).buildResources("dynamodb", containerRequest, "us-east-1", "000000000000");
|
||||
verify(arnBuilder).buildResources(eq("dynamodb"), any(), eq(containerRequest), eq("us-east-1"), eq("000000000000"), eq("aws"));
|
||||
verify(containerRequest, never()).abortWith(any());
|
||||
}
|
||||
|
||||
@@ -1194,7 +1191,7 @@ class IamEnforcementFilterTest {
|
||||
when(actionRegistry.resolve("dynamodb", containerRequest)).thenReturn("dynamodb:BatchGetItem");
|
||||
when(iamService.resolveCallerContext(eq("ASIASESSION"), any()))
|
||||
.thenReturn(CallerContext.of(List.of("{}")));
|
||||
when(arnBuilder.buildResources("dynamodb", containerRequest, "us-east-1", "000000000000"))
|
||||
when(arnBuilder.buildResources(eq("dynamodb"), any(), eq(containerRequest), eq("us-east-1"), eq("000000000000"), eq("aws")))
|
||||
.thenReturn(List.of(
|
||||
"arn:aws:dynamodb:us-east-1:000000000000:table/TableA",
|
||||
"arn:aws:dynamodb:us-east-1:000000000000:table/TableB"
|
||||
@@ -1252,7 +1249,7 @@ class IamEnforcementFilterTest {
|
||||
when(actionRegistry.resolve("dynamodb", containerRequest)).thenReturn("dynamodb:BatchGetItem");
|
||||
when(iamService.resolveCallerContext(eq("ASIASESSION"), any()))
|
||||
.thenReturn(CallerContext.of(List.of("{}")));
|
||||
when(arnBuilder.buildResources("dynamodb", containerRequest, "us-east-1", "000000000000"))
|
||||
when(arnBuilder.buildResources(eq("dynamodb"), any(), eq(containerRequest), eq("us-east-1"), eq("000000000000"), eq("aws")))
|
||||
.thenReturn(List.of(
|
||||
"arn:aws:dynamodb:us-east-1:000000000000:table/TableA",
|
||||
"arn:aws:dynamodb:us-east-1:000000000000:table/TableB"
|
||||
@@ -1481,7 +1478,7 @@ class IamEnforcementFilterTest {
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:ListBucket","Resource":"*"}
|
||||
]}""")));
|
||||
when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
|
||||
when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws")))
|
||||
.thenReturn(List.of("arn:aws:s3:::bucket"));
|
||||
when(conditionContextResolver.resolve("s3", "s3:ListBucket", containerRequest))
|
||||
.thenReturn(conditions);
|
||||
@@ -1528,7 +1525,7 @@ class IamEnforcementFilterTest {
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:PutObject","Resource":"*"}
|
||||
]}""")));
|
||||
when(arnBuilder.buildResources(eq("s3"), eq(containerRequest), anyString(), anyString()))
|
||||
when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), anyString(), anyString(), anyString()))
|
||||
.thenReturn(List.of("arn:aws:s3:::bucket/key"));
|
||||
when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.DENY);
|
||||
@@ -1537,7 +1534,7 @@ class IamEnforcementFilterTest {
|
||||
|
||||
// Everything keyed by scope must see the canonical name, not the alias.
|
||||
verify(actionRegistry).resolve("s3", containerRequest);
|
||||
verify(arnBuilder).buildResources(eq("s3"), eq(containerRequest), anyString(), anyString());
|
||||
verify(arnBuilder).buildResources(eq("s3"), any(), eq(containerRequest), anyString(), anyString(), anyString());
|
||||
verify(conditionContextResolver).resolve("s3", "s3:GetObject", containerRequest);
|
||||
// The policy above grants only s3:PutObject, so a GetObject signed as s3express is denied.
|
||||
verify(containerRequest).abortWith(any(Response.class));
|
||||
@@ -1624,7 +1621,7 @@ class IamEnforcementFilterTest {
|
||||
when(actionRegistry.resolve("organizations", containerRequest))
|
||||
.thenReturn("organizations:DescribeOrganization");
|
||||
when(iamService.resolveCallerContext(eq(account), any())).thenReturn(null);
|
||||
when(arnBuilder.buildResources(eq("organizations"), eq(containerRequest), eq("us-east-1"), eq(account)))
|
||||
when(arnBuilder.buildResources(eq("organizations"), any(), eq(containerRequest), eq("us-east-1"), eq(account), eq("aws")))
|
||||
.thenReturn(List.of("*"));
|
||||
when(conditionContextResolver.resolve(eq("organizations"), anyString(), eq(containerRequest)))
|
||||
.thenReturn(null);
|
||||
@@ -1642,7 +1639,7 @@ class IamEnforcementFilterTest {
|
||||
// arnBuilder.buildResources sits after the caller-resolution branch, so it only fires for a request
|
||||
// that was actually evaluated. Without this, the never()-abort assertion would also pass on
|
||||
// a bypass, making it no stronger than the pre-fix behavior.
|
||||
verify(arnBuilder).buildResources(eq("organizations"), eq(containerRequest), eq("us-east-1"), eq(account));
|
||||
verify(arnBuilder).buildResources(eq("organizations"), any(), eq(containerRequest), eq("us-east-1"), eq(account), eq("aws"));
|
||||
}
|
||||
|
||||
// The realistic baseline guardrail from .temp/org-functional-test.sh: DenyLeaveOrg plus a
|
||||
@@ -1825,7 +1822,7 @@ class IamEnforcementFilterTest {
|
||||
.thenReturn(CallerContext.of(List.of(ALLOW_IF_IAM_USER_PRINCIPAL)));
|
||||
String userArn = "arn:aws:iam::" + account + ":user/bob";
|
||||
when(iamService.resolveCallerArns(akid)).thenReturn(Optional.of(new CallerArns(userArn, userArn)));
|
||||
when(arnBuilder.buildResources(eq("organizations"), eq(containerRequest), eq("us-east-1"), eq(account)))
|
||||
when(arnBuilder.buildResources(eq("organizations"), any(), eq(containerRequest), eq("us-east-1"), eq(account), eq("aws")))
|
||||
.thenReturn(List.of("*"));
|
||||
when(conditionContextResolver.resolve(eq("organizations"), anyString(), eq(containerRequest)))
|
||||
.thenReturn(null);
|
||||
@@ -1838,7 +1835,7 @@ class IamEnforcementFilterTest {
|
||||
|
||||
// aws:PrincipalArn matches arn:aws:iam::*:user/* → the conditional Allow grants access.
|
||||
verify(containerRequest, never()).abortWith(any());
|
||||
verify(arnBuilder).buildResources(eq("organizations"), eq(containerRequest), eq("us-east-1"), eq(account));
|
||||
verify(arnBuilder).buildResources(eq("organizations"), any(), eq(containerRequest), eq("us-east-1"), eq(account), eq("aws"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1889,7 +1886,7 @@ class IamEnforcementFilterTest {
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Deny","Action":"s3:PutObject","Resource":"*"}
|
||||
]}""")));
|
||||
when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
|
||||
when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws")))
|
||||
.thenReturn(List.of("arn:aws:s3:::some-bucket/test.txt"));
|
||||
when(conditionContextResolver.resolve("s3", "s3:PutObject", containerRequest))
|
||||
.thenReturn(null);
|
||||
@@ -1925,7 +1922,7 @@ class IamEnforcementFilterTest {
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Deny","Action":"s3:PutObject","Resource":"*"}
|
||||
]}""")));
|
||||
when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
|
||||
when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws")))
|
||||
.thenReturn(List.of("arn:aws:s3:::some-bucket/test.txt"));
|
||||
when(conditionContextResolver.resolve("s3", "s3:PutObject", containerRequest))
|
||||
.thenReturn(null);
|
||||
@@ -1960,7 +1957,7 @@ class IamEnforcementFilterTest {
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:PutObject","Resource":"*"}
|
||||
]}""")));
|
||||
when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
|
||||
when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws")))
|
||||
.thenReturn(List.of("arn:aws:s3:::some-bucket/test.txt"));
|
||||
when(conditionContextResolver.resolve("s3", "s3:PutObject", containerRequest))
|
||||
.thenReturn(null);
|
||||
@@ -2183,7 +2180,7 @@ class IamEnforcementFilterTest {
|
||||
when(containerRequest.getHeaderString("x-amz-bypass-governance-retention")).thenReturn("true");
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:DeleteObjectVersion");
|
||||
when(iamService.resolveCallerContext(eq("AKIABYPASS"), any())).thenReturn(CallerContext.of(List.of()));
|
||||
when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
|
||||
when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws")))
|
||||
.thenReturn(List.of("arn:aws:s3:::bucket/object"));
|
||||
when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
|
||||
@@ -2216,7 +2213,7 @@ class IamEnforcementFilterTest {
|
||||
when(containerRequest.getHeaderString(header)).thenReturn(headerValue);
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn(allowedAction);
|
||||
when(iamService.resolveCallerContext(eq("AKIAEXTRA"), any())).thenReturn(CallerContext.of(List.of()));
|
||||
when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
|
||||
when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws")))
|
||||
.thenReturn(List.of("arn:aws:s3:::bucket/object"));
|
||||
when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), eq(allowedAction), any(), any()))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
|
||||
@@ -2258,7 +2255,7 @@ class IamEnforcementFilterTest {
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:ListBucket","Resource":"*"}
|
||||
]}""")));
|
||||
when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
|
||||
when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws")))
|
||||
.thenReturn(List.of("arn:aws:s3:::partner-bucket"));
|
||||
when(conditionContextResolver.resolve("s3", "s3:ListBucket", containerRequest))
|
||||
.thenReturn(conditions);
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.RequestResourceMembers.ArnFormat;
|
||||
import io.github.hectorvent.floci.core.common.RequestResourceMembers.Member;
|
||||
import io.github.hectorvent.floci.core.common.RequestResourceMembers.Resource;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import org.junit.jupiter.api.DynamicTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestFactory;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The vendored table of the resources each operation's request names, and that {@link RequestResources} reads every
|
||||
* resource it gives, from a JSON body and from Query form parameters.
|
||||
*/
|
||||
class RequestResourceMembersTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
void theTableReadsItsNamespacesAndGivesEachTypeItNamesAnArnFormat() {
|
||||
RequestResourceMembers.Table table = RequestResourceMembers.table();
|
||||
assertTrue(table.namespaces().containsAll(List.of("cognito-idp", "ecr", "elasticloadbalancing", "states")));
|
||||
assertTrue(table.handBuilt().contains("lambda"));
|
||||
assertTrue(table.namespaces().stream().noneMatch(table.handBuilt()::contains));
|
||||
assertTrue(table.namespaces().stream().noneMatch(table.notCovered()::contains));
|
||||
assertTrue(table.otherNamespaces().stream().noneMatch(table.notCovered()::contains));
|
||||
table.operations().forEach((operation, resources) -> {
|
||||
Map<String, ArnFormat> formats = table.formats().get(operation.substring(0, operation.indexOf(':')));
|
||||
resources.forEach(resource -> assertTrue(formats.keySet().containsAll(resource.types()), operation));
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void anArnFormatMatchesAnArnOfItsTypeAndNoOther() {
|
||||
ArnFormat group = format("arn:${Partition}:elasticloadbalancing:${Region}:${Account}:targetgroup/${TargetGroupName}/${TargetGroupId}");
|
||||
assertTrue(group.pattern().matcher("arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/web/abc").matches());
|
||||
assertTrue(group.pattern().matcher("arn:aws-cn:elasticloadbalancing:cn-north-1:000000000000:targetgroup/a/b").matches());
|
||||
assertFalse(group.pattern().matcher("arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/app/a/b").matches());
|
||||
assertFalse(group.pattern().matcher("arn:aws:iam::000000000000:role/targetgroup/a/b").matches());
|
||||
assertFalse(group.pattern().matcher("arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup//b").matches());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnqualifiedTypesArnIsCheckedWithoutItsQualifier() {
|
||||
String machine = "arn:aws:states:us-east-1:000000000000:stateMachine:orders";
|
||||
String format = "arn:${Partition}:states:${Region}:${Account}:stateMachine:${StateMachineName}";
|
||||
ArnFormat unqualified = new ArnFormat(format, RequestResourceMembers.pattern(format), true);
|
||||
assertEquals(machine, unqualified.checked(machine + ":PROD"));
|
||||
assertEquals(machine, unqualified.checked(machine));
|
||||
assertEquals(machine + ":PROD", format(unqualified.format()).checked(machine + ":PROD"));
|
||||
assertTrue(RequestResourceMembers.table().formats().get("states").get("statemachine").unqualified());
|
||||
assertFalse(RequestResourceMembers.table().formats().get("states").get("execution").unqualified());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMalformedTableFailsToLoad() {
|
||||
assertThrows(IllegalStateException.class, () -> parse("{\"operations\":{}}"));
|
||||
// An operation of a namespace the file does not read.
|
||||
assertThrows(IllegalStateException.class, () -> parse("{\"namespaces\":{\"a\":[]},\"arnFormats\":{},"
|
||||
+ "\"operations\":{\"b:Op\":{\"resources\":[]}}}"));
|
||||
// A type with no format, a variable the format does not have, a member that is no member.
|
||||
String formats = "\"arnFormats\":{\"a\":{\"thing\":\"arn:${Partition}:a:${Region}:${Account}:thing/${ThingName}\"}}";
|
||||
assertThrows(IllegalStateException.class, () -> parse(document(formats, "{\"types\":[\"other\"],\"arn\":\"Arn\"}")));
|
||||
assertThrows(IllegalStateException.class, () -> parse(document(formats, "{\"type\":\"thing\",\"fill\":{\"Other\":\"Name\"}}")));
|
||||
assertThrows(IllegalStateException.class, () -> parse(document(formats, "{\"types\":[\"thing\"],\"arn\":\"a.b\"}")));
|
||||
assertThrows(IllegalStateException.class, () -> parse(
|
||||
"{\"namespaces\":{\"a\":[]},\"arnFormats\":{\"a\":{\"thing\":\"*\"}},\"operations\":{\"a:Op\":{\"resources\":[]}}}"));
|
||||
// A type made under a parent whose format it does not extend by one id.
|
||||
for (String part : List.of("part/${PartName}", "part/${ThingName}/${A}/${B}", "thing/${ThingName}/${PartId}")) {
|
||||
assertThrows(IllegalStateException.class, () -> parse("{\"namespaces\":{\"a\":[]},\"arnFormats\":{\"a\":{"
|
||||
+ "\"thing\":\"arn:${Partition}:a:${Region}:${Account}:thing/${ThingName}\","
|
||||
+ "\"part\":\"arn:${Partition}:a:${Region}:${Account}:" + part + "\"}},\"operations\":{\"a:Op\":"
|
||||
+ "{\"resources\":[],\"creates\":[{\"type\":\"part\",\"parent\":\"thing\",\"arn\":\"ThingArn\"}]}}}"),
|
||||
part);
|
||||
}
|
||||
// An ARN read before more than one character.
|
||||
assertThrows(IllegalStateException.class, () -> parse(document(formats,
|
||||
"{\"types\":[\"thing\"],\"arn\":\"ThingArn\",\"before\":\"##\"}")));
|
||||
// An account from a list, or for a type whose format has no account.
|
||||
assertThrows(IllegalStateException.class, () -> parse(document(formats,
|
||||
"{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"},\"account\":\"Ids[]\"}")));
|
||||
assertThrows(IllegalStateException.class, () -> parse(document(
|
||||
"\"arnFormats\":{\"a\":{\"thing\":\"arn:${Partition}:a:::thing/${ThingName}\"}}",
|
||||
"{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"},\"account\":\"registryId\"}")));
|
||||
// A type checked without a qualifier that has no format, or not given as a list.
|
||||
assertThrows(IllegalStateException.class, () -> parse("{\"namespaces\":{\"a\":[]}," + formats
|
||||
+ ",\"unqualified\":{\"a\":[\"other\"]},\"operations\":{\"a:Op\":{\"resources\":[]}}}"));
|
||||
assertThrows(IllegalStateException.class, () -> parse("{\"namespaces\":{\"a\":[]}," + formats
|
||||
+ ",\"unqualified\":{\"a\":\"thing\"},\"operations\":{\"a:Op\":{\"resources\":[]}}}"));
|
||||
assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", new Member("Names", true)), Map.of(),
|
||||
new Member("registryId", false), null)),
|
||||
parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Names[]\"},"
|
||||
+ "\"account\":\"registryId\"}")).operations().get("a:Op"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Each resource alone, from a request naming it and nothing else, gives exactly its ARN, in the account its
|
||||
* account member names when it has one.
|
||||
*/
|
||||
@TestFactory
|
||||
Stream<DynamicTest> everyResourceOfTheTableIsReadFromAJsonBodyAndAForm() {
|
||||
RequestResourceMembers.Table table = RequestResourceMembers.table();
|
||||
return table.operations().entrySet().stream().flatMap(operation -> operation.getValue().stream()
|
||||
.map(resource -> DynamicTest.dynamicTest(operation.getKey() + " " + resource, () -> {
|
||||
String namespace = operation.getKey().substring(0, operation.getKey().indexOf(':'));
|
||||
String name = operation.getKey().substring(namespace.length() + 1);
|
||||
ArnFormat format = table.formats().get(namespace).get(resource.types().getFirst());
|
||||
String arn = example(format.format());
|
||||
String account = resource.account() != null ? "111122223333" : "000000000000";
|
||||
String expected = resource.arn() != null ? arn : expected(format.format(), resource, account);
|
||||
ObjectNode body = MAPPER.createObjectNode();
|
||||
StringBuilder form = new StringBuilder("Action=" + name);
|
||||
Map<Member, String> values = resource.arn() != null ? Map.of(resource.arn(), arn)
|
||||
: resource.fill().values().stream().distinct().collect(Collectors.toMap(m -> m, m -> "x"));
|
||||
Map<Member, String> given = new LinkedHashMap<>(values);
|
||||
if (resource.account() != null) {
|
||||
given.put(resource.account(), account);
|
||||
}
|
||||
resource.when().forEach((member, allowed) -> {
|
||||
if (!allowed.getFirst().isEmpty()) {
|
||||
given.put(new Member(member, false), allowed.getFirst());
|
||||
}
|
||||
});
|
||||
given.forEach((member, value) -> {
|
||||
if (member.list()) {
|
||||
body.putArray(member.name()).add(value);
|
||||
form.append('&').append(member.name()).append(".member.1=").append(encoded(value));
|
||||
} else {
|
||||
body.put(member.name(), value);
|
||||
form.append('&').append(member.name()).append('=').append(encoded(value));
|
||||
}
|
||||
});
|
||||
assertEquals(List.of(expected), RequestResources.of(operation.getKey(), json(body.toString()),
|
||||
"aws", "us-east-1", "000000000000"), body.toString());
|
||||
assertEquals(List.of(expected), RequestResources.of(operation.getKey(), form(form.toString()),
|
||||
"aws", "us-east-1", "000000000000"), form.toString());
|
||||
})));
|
||||
}
|
||||
|
||||
/** Each resource a create makes under a parent, from a request naming the parent's ARN, is the parent's own. */
|
||||
@TestFactory
|
||||
Stream<DynamicTest> everyResourceACreateMakesIsNamedFromItsParentsArn() {
|
||||
RequestResourceMembers.Table table = RequestResourceMembers.table();
|
||||
return table.creates().entrySet().stream().flatMap(operation -> operation.getValue().stream()
|
||||
.map(created -> DynamicTest.dynamicTest(operation.getKey() + " " + created.type(), () -> {
|
||||
String namespace = operation.getKey().substring(0, operation.getKey().indexOf(':'));
|
||||
String name = operation.getKey().substring(namespace.length() + 1);
|
||||
String parent = example(table.formats().get(namespace).get(created.parent()).format());
|
||||
String child = example(table.formats().get(namespace).get(created.type()).format());
|
||||
String expected = child.substring(0, child.length() - 1) + "*";
|
||||
ObjectNode body = MAPPER.createObjectNode();
|
||||
if (created.arn().list()) {
|
||||
body.putArray(created.arn().name()).add(parent);
|
||||
} else {
|
||||
body.put(created.arn().name(), parent);
|
||||
}
|
||||
String form = "Action=" + name + "&" + created.arn().name() + (created.arn().list() ? ".member.1=" : "=")
|
||||
+ encoded(parent);
|
||||
assertTrue(RequestResources.created(operation.getKey(), json(body.toString()), "aws",
|
||||
"us-east-1", "000000000000").contains(expected), body.toString());
|
||||
assertTrue(RequestResources.created(operation.getKey(), form(form), "aws", "us-east-1",
|
||||
"000000000000").contains(expected), form);
|
||||
})));
|
||||
}
|
||||
|
||||
/** An ARN of the format in the test's partition, Region and account, each other variable {@code x}. */
|
||||
private static String example(String format) {
|
||||
return format.replace("${Partition}", "aws").replace("${Region}", "us-east-1")
|
||||
.replace("${Account}", "000000000000").replaceAll("\\$\\{\\w+}", "x");
|
||||
}
|
||||
|
||||
/** The format in the account with each variable the resource fills {@code x}, and each other open. */
|
||||
private static String expected(String format, Resource resource, String account) {
|
||||
String arn = format.replace("${Partition}", "aws").replace("${Region}", "us-east-1")
|
||||
.replace("${Account}", account);
|
||||
for (String variable : resource.fill().keySet()) {
|
||||
arn = arn.replace("${" + variable + "}", "x");
|
||||
}
|
||||
return arn.replaceAll("\\$\\{\\w+}", "*");
|
||||
}
|
||||
|
||||
private static ArnFormat format(String format) {
|
||||
return new ArnFormat(format, RequestResourceMembers.pattern(format), false);
|
||||
}
|
||||
|
||||
private static String document(String formats, String resource) {
|
||||
return "{\"namespaces\":{\"a\":[]}," + formats + ",\"operations\":{\"a:Op\":{\"resources\":[" + resource + "]}}}";
|
||||
}
|
||||
|
||||
private static RequestResourceMembers.Table parse(String document) throws Exception {
|
||||
return RequestResourceMembers.parse(new ByteArrayInputStream(document.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
private static RequestResourceMembers.Table parseUnchecked(String document) {
|
||||
try {
|
||||
return parse(document);
|
||||
} catch (Exception e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String encoded(String value) {
|
||||
return URLEncoder.encode(value, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static ContainerRequestContext json(String body) {
|
||||
return request("application/x-amz-json-1.1", body);
|
||||
}
|
||||
|
||||
private static ContainerRequestContext form(String body) {
|
||||
return request("application/x-www-form-urlencoded", body);
|
||||
}
|
||||
|
||||
private static ContainerRequestContext request(String mediaType, String body) {
|
||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||
ContainerRequestContext request = mock(ContainerRequestContext.class);
|
||||
when(request.getMethod()).thenReturn("POST");
|
||||
when(request.getMediaType()).thenReturn(MediaType.valueOf(mediaType));
|
||||
when(request.getEntityStream()).thenAnswer(invocation -> new ByteArrayInputStream(bytes));
|
||||
return request;
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Every IAM namespace Floci serves whose actions the Service Reference gives resource types is one the vendored
|
||||
* table of request resources reads, one whose resources {@code ResourceArnBuilder} builds by hand, or one the table
|
||||
* names as not read yet, so a service Floci adds is not left checking its resources on {@code *} unnoticed.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class RequestResourceNamespacesIntegrationTest {
|
||||
|
||||
@Inject
|
||||
ResolvedServiceCatalog catalog;
|
||||
|
||||
@Test
|
||||
void everyNamespaceFlociServesWithResourceTypesIsReadBuiltByHandOrNamedAsNotReadYet() {
|
||||
Set<String> served = new TreeSet<>();
|
||||
for (ServiceDescriptor descriptor : catalog.all()) {
|
||||
for (String scope : descriptor.credentialScopes()) {
|
||||
served.add(catalog.canonicalCredentialScope(scope));
|
||||
}
|
||||
}
|
||||
Set<String> unread = new TreeSet<>(served);
|
||||
unread.retainAll(RequestResourceMembers.table().otherNamespaces());
|
||||
assertEquals(Set.of(), unread, "add these to NAMESPACES or NOT_COVERED in tools/aws/regen_iam_request_resources.py");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** How {@link RequestResources} builds the ARNs of the resources a request names. */
|
||||
class RequestResourcesTest {
|
||||
|
||||
private static final String MACHINE = "arn:aws:states:us-east-1:000000000000:stateMachine:orders";
|
||||
|
||||
@Test
|
||||
void aMemberHoldingAnArnOfATypeTheActionActsOnNamesThatResource() {
|
||||
assertEquals(List.of(MACHINE), of("states:DescribeStateMachine",
|
||||
json("{\"stateMachineArn\":\"" + MACHINE + "\"}")));
|
||||
}
|
||||
|
||||
/** {@code CreateStateMachine}'s {@code roleArn} is an IAM role, no resource of Step Functions. */
|
||||
@Test
|
||||
void anArnOfAnotherTypeIsNotChecked() {
|
||||
assertEquals(List.of(MACHINE), of("states:CreateStateMachine", json(
|
||||
"{\"name\":\"orders\",\"roleArn\":\"arn:aws:iam::000000000000:role/sfn\",\"definition\":\"{}\"}")));
|
||||
}
|
||||
|
||||
/**
|
||||
* A handler may act on the resource the ARN names or on one of that name in the caller's account or the
|
||||
* request's Region, or both (ECR's tag handlers keep the ARN's account in the request's Region), so each is
|
||||
* checked.
|
||||
*/
|
||||
@Test
|
||||
void anArnOfAnotherAccountOrRegionIsCheckedAsGivenAndAsTheCallersOwn() {
|
||||
String other = "arn:aws:states:eu-west-1:111122223333:stateMachine:orders";
|
||||
assertEquals(List.of(other, "arn:aws:states:us-east-1:111122223333:stateMachine:orders",
|
||||
"arn:aws:states:eu-west-1:000000000000:stateMachine:orders", MACHINE), of("states:DescribeStateMachine",
|
||||
json("{\"stateMachineArn\":\"" + other + "\"}")));
|
||||
assertEquals(List.of("arn:aws:ecr:eu-west-1:111122223333:repository/web",
|
||||
"arn:aws:ecr:us-east-1:111122223333:repository/web", "arn:aws:ecr:eu-west-1:000000000000:repository/web",
|
||||
"arn:aws:ecr:us-east-1:000000000000:repository/web"), of("ecr:TagResource",
|
||||
json("{\"resourceArn\":\"arn:aws:ecr:eu-west-1:111122223333:repository/web\",\"tags\":[]}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTypesVariablesAreFilledFromTheRequestAndAListGivesAResourceForEachValue() {
|
||||
assertEquals(List.of("arn:aws:ecr:us-east-1:000000000000:repository/web",
|
||||
"arn:aws:ecr:us-east-1:000000000000:repository/api"), of("ecr:DescribeRepositories", json(
|
||||
"{\"repositoryNames\":[\"web\",\"api\"]}")));
|
||||
assertEquals(List.of("arn:aws:cognito-idp:us-east-1:000000000000:userpool/us-east-1_abc"),
|
||||
of("cognito-idp:DescribeUserPool", json("{\"UserPoolId\":\"us-east-1_abc\"}")));
|
||||
}
|
||||
|
||||
/** A value that is itself an ARN of the type names that resource. */
|
||||
@Test
|
||||
void aValueThatIsAnArnOfTheTypeNamesItsResource() {
|
||||
assertEquals(List.of("arn:aws:ecr:us-east-1:000000000000:repository/web"), of("ecr:DescribeRepositories", json(
|
||||
"{\"repositoryNames\":[\"arn:aws:ecr:us-east-1:000000000000:repository/web\"]}")));
|
||||
}
|
||||
|
||||
/** The service mints a new target group's id, so it is open. */
|
||||
@Test
|
||||
void aVariableTheRequestDoesNotFillIsOpen() {
|
||||
assertEquals(List.of("arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/web/*"),
|
||||
of("elasticloadbalancing:CreateTargetGroup",
|
||||
form("Action=CreateTargetGroup&Name=web&Protocol=HTTP&Port=80")));
|
||||
}
|
||||
|
||||
/** A v2 load balancer's type, application when none is given, picks the ARN it is created under. */
|
||||
@Test
|
||||
void aLoadBalancerIsCreatedUnderTheArnOfItsType() {
|
||||
String prefix = "arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/";
|
||||
assertEquals(List.of(prefix + "app/web/*"), of("elasticloadbalancing:CreateLoadBalancer",
|
||||
form("Action=CreateLoadBalancer&Name=web")));
|
||||
assertEquals(List.of(prefix + "net/web/*"), of("elasticloadbalancing:CreateLoadBalancer",
|
||||
form("Action=CreateLoadBalancer&Name=web&Type=network")));
|
||||
assertEquals(List.of(prefix + "gwy/web/*"), of("elasticloadbalancing:CreateLoadBalancer",
|
||||
form("Action=CreateLoadBalancer&Name=web&Type=gateway")));
|
||||
assertEquals(List.of(), of("elasticloadbalancing:CreateLoadBalancer",
|
||||
form("Action=CreateLoadBalancer&Name=web&Type=other")));
|
||||
// The classic API names it by LoadBalancerName.
|
||||
assertEquals(List.of(prefix + "classic"), of("elasticloadbalancing:CreateLoadBalancer",
|
||||
form("Action=CreateLoadBalancer&LoadBalancerName=classic&Listeners.member.1.Protocol=HTTP")));
|
||||
}
|
||||
|
||||
/**
|
||||
* A listener is made under a load balancer, and a rule under a listener: their ARNs are the parent's with its
|
||||
* type word replaced and their own id open, of the parent's type.
|
||||
*/
|
||||
@Test
|
||||
void aResourceCreatedUnderAParentIsNamedFromTheParentsArn() {
|
||||
String prefix = "arn:aws:elasticloadbalancing:us-east-1:000000000000:";
|
||||
assertEquals(List.of(prefix + "listener/app/web/abc/*"), created("elasticloadbalancing:CreateListener", form(
|
||||
"Action=CreateListener&LoadBalancerArn=" + prefix + "loadbalancer/app/web/abc&Protocol=HTTP&Port=80")));
|
||||
assertEquals(List.of(prefix + "listener/net/web/abc/*"), created("elasticloadbalancing:CreateListener", form(
|
||||
"Action=CreateListener&LoadBalancerArn=" + prefix + "loadbalancer/net/web/abc&Protocol=TCP&Port=80")));
|
||||
assertEquals(List.of(prefix + "listener-rule/app/web/abc/def/*"), created("elasticloadbalancing:CreateRule",
|
||||
form("Action=CreateRule&ListenerArn=" + prefix + "listener/app/web/abc/def&Priority=1")));
|
||||
// A parent of another account is named as given and as the caller's own.
|
||||
assertEquals(List.of("arn:aws:elasticloadbalancing:us-east-1:111122223333:listener/app/web/abc/*",
|
||||
prefix + "listener/app/web/abc/*"), created("elasticloadbalancing:CreateListener", form(
|
||||
"Action=CreateListener&LoadBalancerArn=arn:aws:elasticloadbalancing:us-east-1:111122223333:"
|
||||
+ "loadbalancer/app/web/abc")));
|
||||
// An ARN of no parent, a create of a type its action acts on, and no create name nothing.
|
||||
assertEquals(List.of(), created("elasticloadbalancing:CreateListener",
|
||||
form("Action=CreateListener&LoadBalancerArn=" + prefix + "targetgroup/web/abc")));
|
||||
assertEquals(List.of(), created("elasticloadbalancing:CreateTargetGroup",
|
||||
form("Action=CreateTargetGroup&Name=web")));
|
||||
assertEquals(List.of(), created("elasticloadbalancing:DeleteListener",
|
||||
form("Action=DeleteListener&ListenerArn=" + prefix + "listener/app/web/abc/def")));
|
||||
}
|
||||
|
||||
/**
|
||||
* The operation is the one the request is dispatched as: an {@code X-Amz-Target} or {@code Action} naming
|
||||
* another, whose members name an allowed resource, does not change what it is checked on.
|
||||
*/
|
||||
@Test
|
||||
void theOperationIsTheOneTheRequestIsDispatchedAsNotOneTheRequestNames() {
|
||||
ContainerRequestContext request = json("{\"name\":\"allowed\",\"stateMachineArn\":\"" + MACHINE + "\"}");
|
||||
when(request.getHeaderString("X-Amz-Target")).thenReturn("AWSStepFunctions.CreateStateMachine");
|
||||
assertEquals(List.of(MACHINE), of("states:DescribeStateMachine", request));
|
||||
String group = "arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/web/1";
|
||||
assertEquals(List.of(group), of("elasticloadbalancing:DeleteTargetGroup",
|
||||
form("Action=CreateTargetGroup&Name=allowed&TargetGroupArn=" + group)));
|
||||
assertEquals(List.of(), created("elasticloadbalancing:DeleteLoadBalancer", form("Action=CreateListener"
|
||||
+ "&LoadBalancerArn=arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/app/web/abc")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFormsListIsReadFromOneToTheFirstMissingNumber() {
|
||||
String first = "arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/a/1";
|
||||
String second = "arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/app/b/2";
|
||||
assertEquals(List.of(first, second), of("elasticloadbalancing:AddTags", form("Action=AddTags"
|
||||
+ "&ResourceArns.member.1=" + first + "&ResourceArns.member.2=" + second
|
||||
+ "&ResourceArns.member.4=arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/c/3"
|
||||
+ "&Tags.member.1.Key=team")));
|
||||
// A classic load balancer goes by its name.
|
||||
assertEquals(List.of("arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/classic"),
|
||||
of("elasticloadbalancing:DeleteLoadBalancer",
|
||||
form("Action=DeleteLoadBalancer&LoadBalancerName=classic")));
|
||||
}
|
||||
|
||||
/**
|
||||
* A member is read as its handler reads it: a list only from a list, so a single name for one gives none, as
|
||||
* ECR's handler then lists every repository, a number, boolean or null as its text, and a structure as none.
|
||||
*/
|
||||
@Test
|
||||
void aMemberIsReadAsItsHandlerReadsIt() {
|
||||
assertEquals(List.of(), of("ecr:DescribeRepositories", json("{\"repositoryNames\":\"allowed\"}")));
|
||||
assertEquals(List.of("arn:aws:ecr:us-east-1:000000000000:repository/123",
|
||||
"arn:aws:ecr:us-east-1:000000000000:repository/null"),
|
||||
of("ecr:DescribeRepositories", json("{\"repositoryNames\":[123,{\"a\":1},null]}")));
|
||||
assertEquals(List.of("arn:aws:ecr:us-east-1:000000000000:repository/7"),
|
||||
of("ecr:DeleteRepository", json("{\"repositoryName\":7}")));
|
||||
assertEquals(List.of(), of("ecr:DeleteRepository", json("{\"repositoryName\":[\"web\"]}")));
|
||||
}
|
||||
|
||||
/**
|
||||
* ECR's {@code registryId} selects the registry its handler acts in, so the repositories are that account's;
|
||||
* one that is no account id names none.
|
||||
*/
|
||||
@Test
|
||||
void aRepositoryIsInTheRegistryTheRequestNames() {
|
||||
assertEquals(List.of("arn:aws:ecr:us-east-1:111122223333:repository/web"), of("ecr:DescribeRepositories",
|
||||
json("{\"registryId\":\"111122223333\",\"repositoryNames\":[\"web\"]}")));
|
||||
assertEquals(List.of("arn:aws:ecr:us-east-1:000000000000:repository/web"), of("ecr:DescribeRepositories",
|
||||
json("{\"repositoryNames\":[\"web\"]}")));
|
||||
assertEquals(List.of(), of("ecr:DescribeRepositories",
|
||||
json("{\"registryId\":\"1:2\",\"repositoryNames\":[\"web\"]}")));
|
||||
// A JSON null is no registry, as ECR reads it: the caller's.
|
||||
assertEquals(List.of("arn:aws:ecr:us-east-1:000000000000:repository/web"), of("ecr:DescribeRepositories",
|
||||
json("{\"registryId\":null,\"repositoryNames\":[\"web\"]}")));
|
||||
// The scanning configuration's request has no registryId: its repositories are the caller's.
|
||||
assertEquals(List.of("arn:aws:ecr:us-east-1:000000000000:repository/web"),
|
||||
of("ecr:BatchGetRepositoryScanningConfiguration",
|
||||
json("{\"registryId\":\"111122223333\",\"repositoryNames\":[\"web\"]}")));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code StartExecution} takes Step Functions Local's {@code <stateMachineArn>#<test case>} and runs the
|
||||
* machine the part before the {@code #} names, so that machine is checked; other operations read it whole.
|
||||
*/
|
||||
@Test
|
||||
void aStateMachinesTestCaseIsCheckedOnTheMachineItRuns() {
|
||||
assertEquals(List.of(MACHINE), of("states:StartExecution",
|
||||
json("{\"stateMachineArn\":\"" + MACHINE + "#HappyPath\"}")));
|
||||
assertEquals(List.of(MACHINE), of("states:StartSyncExecution", json("{\"stateMachineArn\":\"" + MACHINE + "#\"}")));
|
||||
assertEquals(List.of(MACHINE + "#x"), of("states:DescribeStateMachine",
|
||||
json("{\"stateMachineArn\":\"" + MACHINE + "#x\"}")));
|
||||
assertEquals(List.of("arn:aws:states:us-east-1:000000000000:execution:orders:*"), created("states:StartExecution",
|
||||
json("{\"stateMachineArn\":\"" + MACHINE + "#HappyPath\"}")));
|
||||
}
|
||||
|
||||
/**
|
||||
* Step Functions checks a version or an alias on its state machine's ARN, so a request naming one is checked on
|
||||
* the state machine, and an execution it starts is the state machine's; other types keep their ARN whole.
|
||||
*/
|
||||
@Test
|
||||
void aVersionOrAnAliasIsCheckedOnItsStateMachine() {
|
||||
assertEquals(List.of(MACHINE), of("states:DescribeStateMachineAlias",
|
||||
json("{\"stateMachineAliasArn\":\"" + MACHINE + ":PROD\"}")));
|
||||
assertEquals(List.of(MACHINE), of("states:DeleteStateMachineVersion",
|
||||
json("{\"stateMachineVersionArn\":\"" + MACHINE + ":3\"}")));
|
||||
assertEquals(List.of(MACHINE), of("states:DescribeStateMachine", json("{\"stateMachineArn\":\"" + MACHINE + ":1\"}")));
|
||||
assertEquals(List.of(MACHINE), of("states:StartExecution",
|
||||
json("{\"stateMachineArn\":\"" + MACHINE + ":PROD#HappyPath\"}")));
|
||||
assertEquals(List.of("arn:aws:states:us-east-1:000000000000:execution:orders:*"), created("states:StartExecution",
|
||||
json("{\"stateMachineArn\":\"" + MACHINE + ":PROD\"}")));
|
||||
String execution = "arn:aws:states:us-east-1:000000000000:execution:orders:run-1";
|
||||
assertEquals(List.of(execution), of("states:DescribeExecution", json("{\"executionArn\":\"" + execution + "\"}")));
|
||||
}
|
||||
|
||||
/** A request value is a name, so a {@code ${...}} in it is kept, not read as a variable of the format. */
|
||||
@Test
|
||||
void aValueIsTakenLiterally() {
|
||||
assertEquals(List.of("arn:aws:ecr:us-east-1:000000000000:repository/${Account}"),
|
||||
of("ecr:DescribeRepositories", json(
|
||||
"{\"repositoryNames\":[\"${Account}\"]}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestNamingNoResourceOrOfANamespaceTheTableDoesNotReadIsCheckedOnStar() {
|
||||
assertEquals(List.of(), of("ecr:DescribeRepositories", json("{}")));
|
||||
assertEquals(List.of(), of("ecr:GetAuthorizationToken", json("{}")));
|
||||
assertEquals(List.of(), of("ecr:NoSuchOperation", json("{\"repositoryName\":\"web\"}")));
|
||||
assertEquals(List.of(), of(null, json("{\"repositoryName\":\"web\"}")));
|
||||
assertEquals(List.of(), of("lambda:GetFunction", json("{\"FunctionName\":\"f\"}")));
|
||||
}
|
||||
|
||||
private static List<String> created(String operation, ContainerRequestContext request) {
|
||||
return RequestResources.created(operation, request, "aws", "us-east-1", "000000000000");
|
||||
}
|
||||
|
||||
private static List<String> of(String operation, ContainerRequestContext request) {
|
||||
return RequestResources.of(operation, request, "aws", "us-east-1", "000000000000");
|
||||
}
|
||||
|
||||
private static ContainerRequestContext json(String body) {
|
||||
return request("application/x-amz-json-1.1", body);
|
||||
}
|
||||
|
||||
private static ContainerRequestContext form(String body) {
|
||||
return request("application/x-www-form-urlencoded", body);
|
||||
}
|
||||
|
||||
private static ContainerRequestContext request(String mediaType, String body) {
|
||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||
ContainerRequestContext request = mock(ContainerRequestContext.class);
|
||||
when(request.getMethod()).thenReturn("POST");
|
||||
when(request.getMediaType()).thenReturn(MediaType.valueOf(mediaType));
|
||||
when(request.getEntityStream()).thenAnswer(invocation -> new ByteArrayInputStream(bytes));
|
||||
return request;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package io.github.hectorvent.floci.services.ecr;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** How {@link EcrJsonHandler} reads the requests it hands to {@link EcrService}. */
|
||||
class EcrJsonHandlerTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
/**
|
||||
* AWS's {@code BatchGetRepositoryScanningConfiguration} request has no {@code registryId}, so the repositories
|
||||
* are the caller's whatever one the request carries, as IAM checks them.
|
||||
*/
|
||||
@Test
|
||||
void theScanningConfigurationIsOfTheCallersRepositories() throws Exception {
|
||||
EcrService service = mock(EcrService.class);
|
||||
when(service.describeRepositories(List.of("web"), null, "us-east-1")).thenReturn(List.of());
|
||||
EcrJsonHandler handler = new EcrJsonHandler(service, MAPPER);
|
||||
|
||||
assertEquals(200, handler.handle("BatchGetRepositoryScanningConfiguration",
|
||||
MAPPER.readTree("{\"registryId\":\"111122223333\",\"repositoryNames\":[\"web\"]}"), "us-east-1")
|
||||
.getStatus());
|
||||
verify(service).describeRepositories(List.of("web"), null, "us-east-1");
|
||||
}
|
||||
}
|
||||
@@ -149,6 +149,23 @@ class ElbV2ServiceTest {
|
||||
verify(ec2Service, never()).describeSubnets(anyString(), anyList(), any());
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@code Type} outside the model's enum is refused, as AWS refuses it, before anything is looked up or
|
||||
* stored, rather than read as an Application Load Balancer.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"other", "Application", ""})
|
||||
void aLoadBalancerOfATypeOutsideTheEnumIsRefused(String type) {
|
||||
AwsException refusal = assertThrows(AwsException.class, () -> service.createLoadBalancer(REGION,
|
||||
"unknown-type", null, type, null, List.of("subnet-a", "subnet-b"), List.of(), Map.of()));
|
||||
assertEquals("ValidationError", refusal.getErrorCode());
|
||||
assertEquals("1 validation error detected: Value '" + type + "' at 'type' failed to satisfy constraint: "
|
||||
+ "Member must satisfy enum value set: [application, network, gateway]", refusal.getMessage());
|
||||
assertEquals(400, refusal.getHttpStatus());
|
||||
assertTrue(service.describeLoadBalancers(REGION, null, null, null, null).isEmpty());
|
||||
verify(ec2Service, never()).describeSubnets(anyString(), anyList(), any());
|
||||
}
|
||||
|
||||
/** A Network or Gateway Load Balancer can be in a single Availability Zone. */
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"network", "gateway"})
|
||||
|
||||
+456
@@ -0,0 +1,456 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
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.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
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;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* A request of a service whose ARNs the vendored table of request resources gives is checked on the resource it
|
||||
* names, the ARN its handler mints, so a grant scoped to the resource allows it, and the same grant refuses a
|
||||
* request naming another; a deny scoped to the resource holds. Without the table these were checked on {@code *}.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class IamRequestResourceEnforcementIntegrationTest {
|
||||
|
||||
private static final String ADMIN = "test";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ELB = "arn:aws:elasticloadbalancing:" + REGION + ":" + ACCOUNT + ":";
|
||||
/** The AWS Load Balancer Controller's create, tag-on-create and listener statements (its policy v2.14.0). */
|
||||
private static final String CONTROLLER_CREATE = "{\"Effect\":\"Allow\",\"Action\":[\"elasticloadbalancing:CreateLoadBalancer\","
|
||||
+ "\"elasticloadbalancing:CreateTargetGroup\"],\"Resource\":\"*\","
|
||||
+ "\"Condition\":{\"Null\":{\"aws:RequestTag/elbv2.k8s.aws/cluster\":\"false\"}}}";
|
||||
private static final String CONTROLLER_LISTENERS = "{\"Effect\":\"Allow\",\"Action\":[\"elasticloadbalancing:CreateListener\","
|
||||
+ "\"elasticloadbalancing:DeleteListener\",\"elasticloadbalancing:CreateRule\",\"elasticloadbalancing:DeleteRule\"],"
|
||||
+ "\"Resource\":\"*\"}";
|
||||
private static final String CONTROLLER_TAG_LISTENERS = "{\"Effect\":\"Allow\",\"Action\":[\"elasticloadbalancing:AddTags\","
|
||||
+ "\"elasticloadbalancing:RemoveTags\"],\"Resource\":[\"arn:aws:elasticloadbalancing:*:*:listener/net/*/*/*\","
|
||||
+ "\"arn:aws:elasticloadbalancing:*:*:listener/app/*/*/*\",\"arn:aws:elasticloadbalancing:*:*:listener-rule/net/*/*/*\","
|
||||
+ "\"arn:aws:elasticloadbalancing:*:*:listener-rule/app/*/*/*\"]}";
|
||||
private static final String CONTROLLER_TAG_ON_CREATE = "{\"Effect\":\"Allow\",\"Action\":[\"elasticloadbalancing:AddTags\"],"
|
||||
+ "\"Resource\":[\"arn:aws:elasticloadbalancing:*:*:targetgroup/*/*\",\"arn:aws:elasticloadbalancing:*:*:loadbalancer/net/*/*\","
|
||||
+ "\"arn:aws:elasticloadbalancing:*:*:loadbalancer/app/*/*\"],\"Condition\":{\"StringEquals\":"
|
||||
+ "{\"elasticloadbalancing:CreateAction\":[\"CreateTargetGroup\",\"CreateLoadBalancer\"]},"
|
||||
+ "\"Null\":{\"aws:RequestTag/elbv2.k8s.aws/cluster\":\"false\"}}}";
|
||||
private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory());
|
||||
private static final String PASS = "{\\\"StartAt\\\":\\\"P\\\",\\\"States\\\":{\\\"P\\\":{\\\"Type\\\":\\\"Pass\\\",\\\"End\\\":true}}}";
|
||||
|
||||
@TestHTTPResource("/")
|
||||
static URI baseUri;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTargetGroupIsCheckedOnItsArnAndANewOneOnItsName() {
|
||||
String name = "res-tg-" + suffix();
|
||||
String arn = admin("elasticloadbalancing").formParam("Action", "CreateTargetGroup").formParam("Version", "2015-12-01")
|
||||
.formParam("Name", name).formParam("Protocol", "HTTP").formParam("Port", "80").formParam("TargetType", "ip")
|
||||
.post("/").then().statusCode(200).extract()
|
||||
.path("CreateTargetGroupResponse.CreateTargetGroupResult.TargetGroups.member.TargetGroupArn");
|
||||
cleanup.register(() -> admin("elasticloadbalancing").formParam("Action", "DeleteTargetGroup")
|
||||
.formParam("Version", "2015-12-01").formParam("TargetGroupArn", arn).post("/"));
|
||||
assertEquals(arn.substring(0, arn.lastIndexOf('/')), "arn:aws:elasticloadbalancing:" + REGION + ":" + ACCOUNT
|
||||
+ ":targetgroup/" + name);
|
||||
|
||||
User user = user("res-tg");
|
||||
user.policy(allowOn("elasticloadbalancing:ModifyTargetGroupAttributes", arn));
|
||||
modifyAttributes(user, arn).statusCode(200);
|
||||
refused(modifyAttributes(user, arn + "0"), "elasticloadbalancing:ModifyTargetGroupAttributes");
|
||||
|
||||
// A new target group's id is the service's to mint, so a grant on its name covers it.
|
||||
String created = "res-new-" + suffix();
|
||||
user.policy(allowOn("elasticloadbalancing:CreateTargetGroup", "arn:aws:elasticloadbalancing:" + REGION + ":"
|
||||
+ ACCOUNT + ":targetgroup/" + created + "/*"));
|
||||
refused(createTargetGroup(user, created + "-other"), "elasticloadbalancing:CreateTargetGroup");
|
||||
String createdArn = createTargetGroup(user, created).statusCode(200).extract()
|
||||
.path("CreateTargetGroupResponse.CreateTargetGroupResult.TargetGroups.member.TargetGroupArn");
|
||||
cleanup.register(() -> admin("elasticloadbalancing").formParam("Action", "DeleteTargetGroup")
|
||||
.formParam("Version", "2015-12-01").formParam("TargetGroupArn", createdArn).post("/"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The AWS Load Balancer Controller's policy creates on {@code *} with its cluster tag, and tags at creation only
|
||||
* a target group or an application or network load balancer, as {@code elasticloadbalancing:CreateAction}
|
||||
* says; these statements are the published policy's.
|
||||
*/
|
||||
@Test
|
||||
void theLoadBalancerControllersPolicyCreatesTaggedTargetGroupsAndLoadBalancers() {
|
||||
User user = user("res-alb-controller");
|
||||
user.policy(CONTROLLER_CREATE + "," + CONTROLLER_TAG_ON_CREATE);
|
||||
String group = "res-ctl-" + suffix();
|
||||
String arn = tagged(user.query("elasticloadbalancing", "CreateTargetGroup").formParam("Version", "2015-12-01")
|
||||
.formParam("Name", group).formParam("Protocol", "HTTP").formParam("Port", "80").formParam("TargetType", "ip"))
|
||||
.post("/").then().statusCode(200).extract()
|
||||
.path("CreateTargetGroupResponse.CreateTargetGroupResult.TargetGroups.member.TargetGroupArn");
|
||||
cleanup.register(() -> admin("elasticloadbalancing").formParam("Action", "DeleteTargetGroup")
|
||||
.formParam("Version", "2015-12-01").formParam("TargetGroupArn", arn).post("/"));
|
||||
refused(createTargetGroup(user, group + "-untagged"), "elasticloadbalancing:CreateTargetGroup");
|
||||
|
||||
// Authorized, a load balancer with no subnets is refused by Elastic Load Balancing, not by IAM.
|
||||
tagged(user.query("elasticloadbalancing", "CreateLoadBalancer").formParam("Version", "2015-12-01")
|
||||
.formParam("Name", "res-ctl-alb")).post("/").then().statusCode(400).body(containsString("ValidationError"));
|
||||
tagged(user.query("elasticloadbalancing", "CreateLoadBalancer").formParam("Version", "2015-12-01")
|
||||
.formParam("Name", "res-ctl-nlb").formParam("Type", "network")).post("/").then().statusCode(400)
|
||||
.body(containsString("ValidationError"));
|
||||
refused(user.query("elasticloadbalancing", "CreateLoadBalancer").formParam("Version", "2015-12-01")
|
||||
.formParam("Name", "res-ctl-untagged").post("/").then(), "elasticloadbalancing:CreateLoadBalancer");
|
||||
}
|
||||
|
||||
/**
|
||||
* A listener's and a rule's tags go to the new listener and rule, so the controller's grant of {@code AddTags} on
|
||||
* listeners and rules covers a tagged {@code CreateListener} and {@code CreateRule}, which act on a load balancer
|
||||
* and a listener.
|
||||
*/
|
||||
@Test
|
||||
void theLoadBalancerControllersPolicyCreatesTaggedListenersAndRules() {
|
||||
User user = user("res-alb-listener");
|
||||
user.policy(CONTROLLER_LISTENERS);
|
||||
refused(createListener(user), "elasticloadbalancing:AddTags");
|
||||
refused(createRule(user), "elasticloadbalancing:AddTags");
|
||||
|
||||
// Authorized, a listener of no load balancer and a rule of no listener are refused by Elastic Load Balancing.
|
||||
user.policy(CONTROLLER_LISTENERS + "," + CONTROLLER_TAG_LISTENERS);
|
||||
createListener(user).statusCode(400).body(containsString("LoadBalancerNotFound"));
|
||||
createRule(user).statusCode(400).body(containsString("ListenerNotFound"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A v2 {@code CreateLoadBalancer} of a {@code Type} outside the enum names no v2 load balancer for IAM to check,
|
||||
* and Elastic Load Balancing refuses it, as AWS does, so a grant on a classic load balancer's name does not
|
||||
* create a v2 one under another.
|
||||
*/
|
||||
@Test
|
||||
void aLoadBalancerOfATypeOutsideTheEnumIsNotCreatedUnderAnotherName() {
|
||||
String name = "res-protected-" + suffix();
|
||||
User user = user("res-lb-type");
|
||||
user.policy(allowOn("elasticloadbalancing:CreateLoadBalancer", ELB + "loadbalancer/res-allowed"));
|
||||
user.query("elasticloadbalancing", "CreateLoadBalancer").formParam("Version", "2015-12-01")
|
||||
.formParam("Name", name).formParam("Type", "other").formParam("LoadBalancerName", "res-allowed")
|
||||
.formParam("Subnets.member.1", "subnet-a").formParam("Subnets.member.2", "subnet-b").post("/").then()
|
||||
.statusCode(400).body(containsString("ValidationError"))
|
||||
.body(containsString("Member must satisfy enum value set: [application, network, gateway]"));
|
||||
admin("elasticloadbalancing").formParam("Action", "DescribeLoadBalancers").formParam("Version", "2015-12-01")
|
||||
.post("/").then().statusCode(200).body(not(containsString(name)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStateMachineIsCheckedOnItsArnAndADenyOnItHolds() {
|
||||
String name = "res-sm-" + suffix();
|
||||
String arn = createStateMachine(name);
|
||||
assertEquals("arn:aws:states:" + REGION + ":" + ACCOUNT + ":stateMachine:" + name, arn);
|
||||
|
||||
User user = user("res-sm");
|
||||
user.policy(allowOn("states:DescribeStateMachine", arn));
|
||||
describeStateMachine(user, arn).statusCode(200);
|
||||
refusedJson(describeStateMachine(user, arn + "-other"), "states:DescribeStateMachine");
|
||||
|
||||
user.policy(allowOn("states:DescribeStateMachine", "*") + ",{\"Effect\":\"Deny\",\"Action\":\"states:*\","
|
||||
+ "\"Resource\":\"" + arn + "\"}");
|
||||
refusedJson(describeStateMachine(user, arn), "states:DescribeStateMachine");
|
||||
}
|
||||
|
||||
/**
|
||||
* Over the Smithy RPC v2 route a request is checked for the operation its path dispatches, not one an
|
||||
* {@code X-Amz-Target} it carries names: a grant on one state machine allows describing it there, and a
|
||||
* request whose header names a create of that machine does not describe another.
|
||||
*/
|
||||
@Test
|
||||
void aStateMachineIsCheckedForTheOperationTheRpcV2RouteDispatches() throws IOException {
|
||||
String allowedName = "res-rpc-" + suffix();
|
||||
String allowed = createStateMachine(allowedName);
|
||||
String other = createStateMachine("res-rpc-other-" + suffix());
|
||||
User user = user("res-rpc");
|
||||
user.policy(allowOn("states:DescribeStateMachine", allowed));
|
||||
user.cbor("states").body(CBOR_MAPPER.writeValueAsBytes(Map.of("stateMachineArn", allowed)))
|
||||
.post("/service/SFN/operation/DescribeStateMachine").then().statusCode(200);
|
||||
|
||||
byte[] body = CBOR_MAPPER.writeValueAsBytes(Map.of("name", allowedName, "stateMachineArn", other));
|
||||
JsonNode error = CBOR_MAPPER.readTree(user.cbor("states")
|
||||
.header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine").body(body)
|
||||
.post("/service/SFN/operation/DescribeStateMachine").then().statusCode(403).extract().asByteArray());
|
||||
assertEquals("AccessDeniedException", error.path("__type").asText());
|
||||
assertTrue(error.path("message").asText().contains("states:DescribeStateMachine"), error.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code StartExecution} runs the machine before a Step Functions Local test case's {@code #}, so a grant on
|
||||
* that machine allows a start that names a test case, and a deny on it holds.
|
||||
*/
|
||||
@Test
|
||||
void aStateMachinesTestCaseIsCheckedOnTheMachineItRuns() {
|
||||
String arn = createStateMachine("res-tc-" + suffix());
|
||||
User user = user("res-tc");
|
||||
user.policy(allowOn("states:StartExecution", arn));
|
||||
startExecution(user, arn + "#").statusCode(200);
|
||||
|
||||
user.policy(allowOn("states:StartExecution", "*") + ",{\"Effect\":\"Deny\",\"Action\":\"states:StartExecution\","
|
||||
+ "\"Resource\":\"" + arn + "\"}");
|
||||
refusedJson(startExecution(user, arn + "#"), "states:StartExecution");
|
||||
}
|
||||
|
||||
/**
|
||||
* Step Functions checks a version or an alias on its state machine's ARN, so a grant on the state machine
|
||||
* allows describing its alias and starting it through either, and a deny on it holds for both.
|
||||
*/
|
||||
@Test
|
||||
void aVersionOrAnAliasIsCheckedOnItsStateMachine() {
|
||||
String arn = createStateMachine("res-alias-" + suffix());
|
||||
String version = admin("states").header("X-Amz-Target", "AWSStepFunctions.PublishStateMachineVersion")
|
||||
.contentType("application/x-amz-json-1.0").body("{\"stateMachineArn\":\"" + arn + "\"}")
|
||||
.post("/").then().statusCode(200).extract().path("stateMachineVersionArn");
|
||||
String alias = admin("states").header("X-Amz-Target", "AWSStepFunctions.CreateStateMachineAlias")
|
||||
.contentType("application/x-amz-json-1.0").body("{\"name\":\"PROD\",\"routingConfiguration\":"
|
||||
+ "[{\"stateMachineVersionArn\":\"" + version + "\",\"weight\":100}]}")
|
||||
.post("/").then().statusCode(200).extract().path("stateMachineAliasArn");
|
||||
assertEquals(arn + ":PROD", alias);
|
||||
|
||||
User user = user("res-alias");
|
||||
user.policy(allowOn("states:DescribeStateMachineAlias", arn) + "," + allowOn("states:StartExecution", arn));
|
||||
user.json("states", "AWSStepFunctions.DescribeStateMachineAlias", "1.0")
|
||||
.body("{\"stateMachineAliasArn\":\"" + alias + "\"}").post("/").then().statusCode(200);
|
||||
startExecution(user, alias).statusCode(200);
|
||||
startExecution(user, version).statusCode(200);
|
||||
|
||||
user.policy(allowOn("states:StartExecution", "*") + ",{\"Effect\":\"Deny\",\"Action\":\"states:StartExecution\","
|
||||
+ "\"Resource\":\"" + arn + "\"}");
|
||||
refusedJson(startExecution(user, alias), "states:StartExecution");
|
||||
refusedJson(startExecution(user, version), "states:StartExecution");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aUserPoolIsCheckedOnTheArnItsIdNames() {
|
||||
String id = admin("cognito-idp").header("X-Amz-Target", "AWSCognitoIdentityProviderService.CreateUserPool")
|
||||
.contentType("application/x-amz-json-1.1").body("{\"PoolName\":\"res-pool-" + suffix() + "\"}")
|
||||
.post("/").then().statusCode(200).extract().path("UserPool.Id");
|
||||
String arn = admin("cognito-idp").header("X-Amz-Target", "AWSCognitoIdentityProviderService.DescribeUserPool")
|
||||
.contentType("application/x-amz-json-1.1").body("{\"UserPoolId\":\"" + id + "\"}")
|
||||
.post("/").then().statusCode(200).extract().path("UserPool.Arn");
|
||||
cleanup.register(() -> admin("cognito-idp").header("X-Amz-Target", "AWSCognitoIdentityProviderService.DeleteUserPool")
|
||||
.contentType("application/x-amz-json-1.1").body("{\"UserPoolId\":\"" + id + "\"}").post("/"));
|
||||
assertEquals("arn:aws:cognito-idp:" + REGION + ":" + ACCOUNT + ":userpool/" + id, arn);
|
||||
|
||||
User user = user("res-pool");
|
||||
user.policy(allowOn("cognito-idp:DescribeUserPool", arn));
|
||||
describeUserPool(user, id).statusCode(200);
|
||||
refusedJson(describeUserPool(user, id + "x"), "cognito-idp:DescribeUserPool");
|
||||
}
|
||||
|
||||
/** A repository is checked on the ARN its name gives, whether or not it exists. */
|
||||
@Test
|
||||
void aRepositoryIsCheckedOnTheArnItsNameGives() {
|
||||
String name = "res-repo-" + suffix();
|
||||
User user = user("res-repo");
|
||||
user.policy(allowOn("ecr:DescribeRepositories", "arn:aws:ecr:" + REGION + ":" + ACCOUNT + ":repository/" + name));
|
||||
describeRepositories(user, name).statusCode(400).body(containsString("RepositoryNotFoundException"));
|
||||
refusedJson(describeRepositories(user, name + "-other"), "ecr:DescribeRepositories");
|
||||
}
|
||||
|
||||
/**
|
||||
* A list given as one name names no repository, as ECR's handler then lists every one, so a grant on that
|
||||
* repository alone does not allow it.
|
||||
*/
|
||||
@Test
|
||||
void aRepositoryListGivenAsOneNameNamesNone() {
|
||||
String name = "res-repo-" + suffix();
|
||||
User user = user("res-repo-list");
|
||||
user.policy(allowOn("ecr:DescribeRepositories", "arn:aws:ecr:" + REGION + ":" + ACCOUNT + ":repository/" + name));
|
||||
refusedJson(describeRepositoriesWith(user, "{\"repositoryNames\":\"" + name + "\"}"), "ecr:DescribeRepositories");
|
||||
}
|
||||
|
||||
/** A repository is checked in the registry the request's {@code registryId} selects, the one ECR acts in. */
|
||||
@Test
|
||||
void aRepositoryIsCheckedInTheRegistryItsRequestNames() {
|
||||
String name = "res-repo-" + suffix();
|
||||
String other = "111122223333";
|
||||
User user = user("res-repo-registry");
|
||||
user.policy(allowOn("ecr:DescribeRepositories", "arn:aws:ecr:" + REGION + ":" + other + ":repository/" + name));
|
||||
describeRepositoriesWith(user, "{\"registryId\":\"" + other + "\",\"repositoryNames\":[\"" + name + "\"]}")
|
||||
.statusCode(400).body(containsString("RepositoryNotFoundException"));
|
||||
refusedJson(describeRepositories(user, name), "ecr:DescribeRepositories");
|
||||
|
||||
user.policy(allowOn("ecr:DescribeRepositories", "arn:aws:ecr:" + REGION + ":" + ACCOUNT + ":repository/" + name));
|
||||
refusedJson(describeRepositoriesWith(user, "{\"registryId\":\"" + other + "\",\"repositoryNames\":[\"" + name
|
||||
+ "\"]}"), "ecr:DescribeRepositories");
|
||||
}
|
||||
|
||||
/** A {@code registryId} of JSON null is no registry, as ECR reads it, so a deny on the caller's repository holds. */
|
||||
@Test
|
||||
void aNullRegistryIsTheCallersOwn() {
|
||||
String name = "res-protected-" + suffix();
|
||||
User user = user("res-repo-null");
|
||||
user.policy(allowOn("ecr:DescribeRepositories", "*") + ",{\"Effect\":\"Deny\",\"Action\":\"ecr:DescribeRepositories\","
|
||||
+ "\"Resource\":\"arn:aws:ecr:" + REGION + ":" + ACCOUNT + ":repository/" + name + "\"}");
|
||||
refusedJson(describeRepositoriesWith(user, "{\"registryId\":null,\"repositoryNames\":[\"" + name + "\"]}"),
|
||||
"ecr:DescribeRepositories");
|
||||
describeRepositoriesWith(user, "{\"registryId\":null,\"repositoryNames\":[\"" + name + "-other\"]}")
|
||||
.statusCode(400).body(containsString("RepositoryNotFoundException"));
|
||||
}
|
||||
|
||||
/**
|
||||
* ECR's tag handlers keep the ARN's account and use the request's Region, so a deny on that repository holds
|
||||
* for an ARN naming it in another Region.
|
||||
*/
|
||||
@Test
|
||||
void aDenyHoldsOnTheRepositoryTheTagHandlersActOn() {
|
||||
String protectedArn = "arn:aws:ecr:" + REGION + ":111122223333:repository/res-protected-" + suffix();
|
||||
User user = user("res-repo-tag");
|
||||
user.policy(allowOn("ecr:TagResource", "*") + ",{\"Effect\":\"Deny\",\"Action\":\"ecr:TagResource\","
|
||||
+ "\"Resource\":\"" + protectedArn + "\"}");
|
||||
refusedJson(user.json("ecr", "AmazonEC2ContainerRegistry_V20150921.TagResource", "1.1")
|
||||
.body("{\"resourceArn\":\"" + protectedArn.replace(REGION, "eu-west-1")
|
||||
+ "\",\"tags\":[{\"Key\":\"a\",\"Value\":\"b\"}]}").post("/").then(), "ecr:TagResource");
|
||||
}
|
||||
|
||||
private static RequestSpecification tagged(RequestSpecification request) {
|
||||
return request.formParam("Tags.member.1.Key", "elbv2.k8s.aws/cluster").formParam("Tags.member.1.Value", "c");
|
||||
}
|
||||
|
||||
private static ValidatableResponse modifyAttributes(User user, String arn) {
|
||||
return user.query("elasticloadbalancing", "ModifyTargetGroupAttributes").formParam("Version", "2015-12-01")
|
||||
.formParam("TargetGroupArn", arn).formParam("Attributes.member.1.Key", "deregistration_delay.timeout_seconds")
|
||||
.formParam("Attributes.member.1.Value", "30").post("/").then();
|
||||
}
|
||||
|
||||
private static ValidatableResponse createTargetGroup(User user, String name) {
|
||||
return user.query("elasticloadbalancing", "CreateTargetGroup").formParam("Version", "2015-12-01")
|
||||
.formParam("Name", name).formParam("Protocol", "HTTP").formParam("Port", "80")
|
||||
.formParam("TargetType", "ip").post("/").then();
|
||||
}
|
||||
|
||||
private static ValidatableResponse createListener(User user) {
|
||||
return tagged(user.query("elasticloadbalancing", "CreateListener").formParam("Version", "2015-12-01")
|
||||
.formParam("LoadBalancerArn", ELB + "loadbalancer/app/res-none/0123456789abcdef")
|
||||
.formParam("Protocol", "HTTP").formParam("Port", "80")
|
||||
.formParam("DefaultActions.member.1.Type", "fixed-response")
|
||||
.formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200")).post("/").then();
|
||||
}
|
||||
|
||||
private static ValidatableResponse createRule(User user) {
|
||||
return tagged(user.query("elasticloadbalancing", "CreateRule").formParam("Version", "2015-12-01")
|
||||
.formParam("ListenerArn", ELB + "listener/app/res-none/0123456789abcdef/0123456789abcdef")
|
||||
.formParam("Priority", "1").formParam("Conditions.member.1.Field", "path-pattern")
|
||||
.formParam("Conditions.member.1.Values.member.1", "/x")
|
||||
.formParam("Actions.member.1.Type", "fixed-response")
|
||||
.formParam("Actions.member.1.FixedResponseConfig.StatusCode", "200")).post("/").then();
|
||||
}
|
||||
|
||||
private String createStateMachine(String name) {
|
||||
String role = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", name + "-role",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"lambda:*\",\"Resource\":\"*\"}]}");
|
||||
String arn = admin("states").header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
|
||||
.contentType("application/x-amz-json-1.0")
|
||||
.body("{\"name\":\"" + name + "\",\"roleArn\":\"" + role + "\",\"definition\":\"" + PASS + "\"}")
|
||||
.post("/").then().statusCode(200).extract().path("stateMachineArn");
|
||||
cleanup.register(() -> admin("states").header("X-Amz-Target", "AWSStepFunctions.DeleteStateMachine")
|
||||
.contentType("application/x-amz-json-1.0").body("{\"stateMachineArn\":\"" + arn + "\"}").post("/"));
|
||||
return arn;
|
||||
}
|
||||
|
||||
private static ValidatableResponse describeStateMachine(User user, String arn) {
|
||||
return user.json("states", "AWSStepFunctions.DescribeStateMachine", "1.0")
|
||||
.body("{\"stateMachineArn\":\"" + arn + "\"}").post("/").then();
|
||||
}
|
||||
|
||||
private static ValidatableResponse startExecution(User user, String arn) {
|
||||
return user.json("states", "AWSStepFunctions.StartExecution", "1.0")
|
||||
.body("{\"stateMachineArn\":\"" + arn + "\"}").post("/").then();
|
||||
}
|
||||
|
||||
private static ValidatableResponse describeUserPool(User user, String id) {
|
||||
return user.json("cognito-idp", "AWSCognitoIdentityProviderService.DescribeUserPool", "1.1")
|
||||
.body("{\"UserPoolId\":\"" + id + "\"}").post("/").then();
|
||||
}
|
||||
|
||||
private static ValidatableResponse describeRepositories(User user, String name) {
|
||||
return describeRepositoriesWith(user, "{\"repositoryNames\":[\"" + name + "\"]}");
|
||||
}
|
||||
|
||||
private static ValidatableResponse describeRepositoriesWith(User user, String body) {
|
||||
return user.json("ecr", "AmazonEC2ContainerRegistry_V20150921.DescribeRepositories", "1.1")
|
||||
.body(body).post("/").then();
|
||||
}
|
||||
|
||||
/** A Query service refuses with {@code AccessDenied}, a 403, naming the permission that is missing. */
|
||||
private static void refused(ValidatableResponse response, String action) {
|
||||
response.statusCode(403).body(containsString("not authorized to perform: " + action));
|
||||
}
|
||||
|
||||
/** A JSON-protocol service refuses with {@code AccessDeniedException}, which those protocols send as a 400. */
|
||||
private static void refusedJson(ValidatableResponse response, String action) {
|
||||
response.statusCode(400).body(containsString("AccessDeniedException"))
|
||||
.body(containsString("not authorized to perform: " + action)).body(not(containsString("NotFound")));
|
||||
}
|
||||
|
||||
private static String allowOn(String action, String resource) {
|
||||
return "{\"Effect\":\"Allow\",\"Action\":\"" + action + "\",\"Resource\":\"" + resource + "\"}";
|
||||
}
|
||||
|
||||
private User user(String name) {
|
||||
String userName = name + "-" + suffix();
|
||||
return new User(userName, EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ADMIN, "iam"),
|
||||
userName).accessKeyId());
|
||||
}
|
||||
|
||||
private static RequestSpecification admin(String service) {
|
||||
return given().header("Authorization", auth(ADMIN, service));
|
||||
}
|
||||
|
||||
private static String suffix() {
|
||||
return Long.toString(System.nanoTime(), 36);
|
||||
}
|
||||
|
||||
/** An IAM user whose one inline policy each test replaces. */
|
||||
private record User(String name, String accessKeyId) {
|
||||
|
||||
void policy(String statements) {
|
||||
admin("iam").formParam("Action", "PutUserPolicy").formParam("UserName", name)
|
||||
.formParam("PolicyName", "p")
|
||||
.formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}")
|
||||
.post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
RequestSpecification query(String service, String action) {
|
||||
return given().header("Authorization", auth(accessKeyId, service)).formParam("Action", action);
|
||||
}
|
||||
|
||||
RequestSpecification json(String service, String target, String version) {
|
||||
return given().header("Authorization", auth(accessKeyId, service)).header("X-Amz-Target", target)
|
||||
.contentType("application/x-amz-json-" + version);
|
||||
}
|
||||
|
||||
RequestSpecification cbor(String service) {
|
||||
return given().header("Authorization", auth(accessKeyId, service)).header("smithy-protocol", "rpc-v2-cbor")
|
||||
.contentType("application/cbor").accept("application/cbor");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1228,6 +1228,26 @@ class ResourceArnBuilderTest {
|
||||
assertEquals("arn:aws:s3:::my-bucket/folder/", arn);
|
||||
}
|
||||
|
||||
// ── The vendored table of request resources ─────────────────────────────────
|
||||
|
||||
/**
|
||||
* A namespace with no branch here is checked on the resources the vendored table finds in its request for the
|
||||
* operation it is dispatched as, and on {@code *} without one or for an operation of another namespace.
|
||||
*/
|
||||
@Test
|
||||
void aNamespaceWithNoBranchIsCheckedOnTheResourcesItsRequestNames() {
|
||||
when(ctx.getMethod()).thenReturn("POST");
|
||||
setJsonBody("{\"UserPoolId\":\"us-east-1_abc\"}");
|
||||
assertEquals(List.of("arn:aws:cognito-idp:us-east-1:000000000000:userpool/us-east-1_abc"), builder.buildResources(
|
||||
"cognito-idp", "cognito-idp:DescribeUserPool", ctx, "us-east-1", "000000000000", "aws"));
|
||||
assertEquals(List.of("*"), builder.buildResources("cognito-idp", ctx, "us-east-1", "000000000000"));
|
||||
assertEquals(List.of("*"), builder.buildResources("glue", "cognito-idp:DescribeUserPool", ctx, "us-east-1",
|
||||
"000000000000", "aws"));
|
||||
setJsonBody("{}");
|
||||
assertEquals(List.of("*"), builder.buildResources("cognito-idp", "cognito-idp:DescribeUserPool", ctx,
|
||||
"us-east-1", "000000000000", "aws"));
|
||||
}
|
||||
|
||||
// ── Lambda ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user