mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(iam): check a create's tags on its own and its tagging action (#6452)
Under IAM enforcement a request that tags the resource it creates was checked only for the operation's own action. AWS also checks the service's tagging action, as the SNS API reference says: "To be able to tag a topic on creation, you must have the sns:CreateTopic and sns:TagResource permissions." A caller allowed to create but not to tag could set at creation the tags that a tag-based policy trusts. The operation's own action did not see the tags either: aws:RequestTag and aws:TagKeys were set only for Logs, S3 and EC2 RunInstances, so a policy allowing sqs:CreateQueue only with aws:RequestTag/team never matched, and one denying it when aws:RequestTag/team is null refused a tagged create. AWS's Service Reference lists the tagging action among each operation's authorized actions and marks the actions that only tag, but does not say which request member carries the tags; botocore's models do. A new generator, tools/aws/regen_iam_tag_on_create.py, joins the two into src/main/resources/aws/iam-tag-on-create.json: 581 operations over 69 namespaces, those Floci authorizes by operation. An operation is in it when the reference lists, beside its own, an action that only tags and adds tags; its tags are read from a top-level member named Tags, TagList, TagSpecifications or the like that holds a tag list or map. 569 are read from the table (579 members), CloudWatch Logs CreateLogGroup is checked by hand as before, and 11 carry no tags this file can read, each with its reason. A correction gives SQS's Query name, Tag.N, and one drops an EC2 IPAM pool's allocation rule, which tags nothing. When a request carries tags, IamEnforcementFilter checks the tagging action for each resource's tags apart, with them as aws:RequestTag/<key> and aws:TagKeys, and, where the action takes it, the operation as its namespace's CreateAction key (ec2:CreateAction is RunInstances for an instance launched with tags). A tag specification's tags are checked on the resource of the type it names, from the ARN the reference gives the type with its name left open (arn:aws:ec2:<Region>:<account>:instance/*), which the table carries for EC2 and RDS; other tags on the resources the operation is checked on. Lambda's CreateFunction is now checked on the function its body names, which the reference gives it, rather than on *, so a grant scoped to the function covers both its action and its tags. The operation's own action is checked with the same two keys, once for each resource's tags, where the reference lists them for it or for a resource it acts on (542 of the 569), keeping any a service's own condition keys set. The table is keyed by operation, so the filter now carries the operation it resolved beside the action, which differs for an operation AWS authorizes under another name (Budgets' CreateBudget is budgets:ModifyBudget). The tags are read as the Floci handler that applies them reads them, so the check sees the tags the resource gets. A form's are read under the SDK's spelling, from 1 to the first number with no key, and under the further spellings the RDS, DocumentDB, Neptune, ElastiCache and Redshift handlers read, numbered as each numbers them; EC2's from every tag specification under either TagSpecification spelling, to the first naming no resource type. A body's member is read under its own name, and CloudWatch's PutMetricAlarm and PutCompositeAlarm also under tags, and a CodeDeploy tag as Key and Value or key and value, each as text whatever it holds, as its handler reads. The tagging action is also checked for tags under any other spelling a handler might read (a name, key or value in any case, any list spelling and number, an object's structures), so none a handler applies goes unchecked. The operation's own action is checked with every reading, its handler's, any other spelling's, and none where its handler reads none, and refused if any is denied, so a deny on a tag holds and a required tag counts only where the handler applies it. make iam-tag-on-create-check, part of aws-data-check, re-derives every member from the pinned botocore; make iam-tag-on-create-verify, part of iam-data-verify, checks every operation against AWS, and the IAM data drift workflow also runs on a change to the table or its generator. Not checked: sts:TagSession in a role's trust policy, service-specific request tag keys such as rds:req-tag, EC2 RequestSpotFleet's nested tags, and the REST services whose routes no rule maps yet.
This commit is contained in:
1 parent
36e244f104
commit
64f4f9e489
18 files changed
+3632
-26
No files matched your search
@@ -0,0 +1,233 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.PassedRoleMembers.Into;
|
||||
import io.github.hectorvent.floci.core.common.PassedRoleMembers.Step;
|
||||
import io.github.hectorvent.floci.core.common.TagOnCreateMembers.Entry;
|
||||
import io.github.hectorvent.floci.core.common.TagOnCreateMembers.Member;
|
||||
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.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
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.assertNull;
|
||||
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 tagging action each operation that tags what it creates needs, and that
|
||||
* {@link TagOnCreate} reads every member it gives, from a JSON body and from Query form parameters.
|
||||
*/
|
||||
class TagOnCreateMembersTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
void theTableReadsTheOperationsOfEveryNamespaceItCoversOnce() {
|
||||
TagOnCreateMembers.Table table = TagOnCreateMembers.table();
|
||||
assertFalse(table.entries().isEmpty());
|
||||
for (String operation : table.entries().keySet()) {
|
||||
assertFalse(table.byHand().contains(operation) || table.notRead().contains(operation), operation);
|
||||
assertTrue(table.namespaces().contains(operation.substring(0, operation.indexOf(':'))), operation);
|
||||
}
|
||||
assertFalse(table.byHand().stream().anyMatch(table.notRead()::contains));
|
||||
assertTrue(table.otherNamespaces().stream().noneMatch(table.namespaces()::contains));
|
||||
assertTrue(table.notCovered().stream().noneMatch(table.namespaces()::contains));
|
||||
}
|
||||
|
||||
/** The operations the table says Floci checks by hand are the ones {@link TagOnCreate} leaves to the filter. */
|
||||
@Test
|
||||
void exactlyTheOperationsCheckedByHandAreLeftToTheFilter() {
|
||||
assertEquals(TagOnCreate.BY_HAND, TagOnCreateMembers.table().byHand());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTagListIsReadAsItsStepsAndATagSpecificationListByItsResourceType() {
|
||||
Member list = member("{\"member\":\"TagSpecification[item].Tag[item]\",\"key\":\"Key\",\"value\":\"Value\","
|
||||
+ "\"resourceType\":\"ResourceType\"}");
|
||||
assertEquals(List.of(new Step("TagSpecification", Into.LIST, "item"), new Step("Tag", Into.LIST, "item")),
|
||||
list.steps());
|
||||
assertEquals("ResourceType", list.resourceType());
|
||||
assertTrue(list.inForm());
|
||||
|
||||
Member named = member("{\"member\":\"Tags[Tag]\",\"key\":\"Key\",\"value\":\"Value\"}");
|
||||
assertEquals(List.of(new Step("Tags", Into.LIST, "Tag")), named.querySteps());
|
||||
assertNull(named.resourceType());
|
||||
assertFalse(member("{\"member\":\"Settings{Tags}.Tags[]\",\"key\":\"Key\",\"value\":\"Value\"}").inForm());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTagMapIsReadFromAFormUnderItsQueryName() {
|
||||
Member map = member("{\"member\":\"tags{}\",\"query\":\"Tag{}\"}");
|
||||
assertEquals(List.of(new Step("tags", Into.MAP, null)), map.steps());
|
||||
assertEquals(List.of(new Step("Tag", Into.MAP, null)), map.querySteps());
|
||||
assertNull(map.key());
|
||||
}
|
||||
|
||||
/** A tag specification's tags are checked on the resource of its type, an ARN the table gives each type. */
|
||||
@Test
|
||||
void theTableGivesAnArnForEachResourceTypeATagSpecificationCanName() {
|
||||
Map<String, String> ec2 = TagOnCreateMembers.table().resourceArns().get("ec2");
|
||||
assertEquals("arn:${Partition}:ec2:${Region}:${Account}:instance/*", ec2.get("instance"));
|
||||
assertEquals("arn:${Partition}:ec2:${Region}::image/*", ec2.get("image"));
|
||||
for (Map.Entry<String, Entry> operation : TagOnCreateMembers.table().entries().entrySet()) {
|
||||
for (Member member : operation.getValue().members()) {
|
||||
assertTrue(member.resourceType() == null || TagOnCreateMembers.table().resourceArns()
|
||||
.containsKey(operation.getKey().substring(0, operation.getKey().indexOf(':'))), operation.getKey());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMalformedTableFailsToLoad() {
|
||||
assertThrows(IllegalStateException.class, () -> parse("{\"operations\":{}}"));
|
||||
assertThrows(IllegalStateException.class, () -> parse("{\"operations\":{\"a:B\":{\"tagging\":[\"a:Tag\"]}}}"));
|
||||
// Several tagging actions are checked by hand, never read from the table.
|
||||
assertThrows(IllegalStateException.class, () -> parse("{\"operations\":{\"a:B\":{\"tagging\":[\"a:T\",\"a:U\"],"
|
||||
+ "\"tags\":[{\"member\":\"Tags{}\"}]}}}"));
|
||||
assertThrows(IllegalStateException.class, () -> member("{\"member\":\"Tags\"}"));
|
||||
assertThrows(IllegalStateException.class, () -> member("{\"member\":\"Tags[]\"}"));
|
||||
assertThrows(IllegalStateException.class, () -> member("{\"member\":\"Tags{}\",\"key\":\"K\",\"value\":\"V\"}"));
|
||||
assertThrows(IllegalStateException.class, () -> member("{\"member\":\"Tags{}\",\"query\":\"Tag[]\"}"));
|
||||
// A resource type belongs to a list of tag specifications, and its namespace's types need ARNs.
|
||||
assertThrows(IllegalStateException.class, () -> member("{\"member\":\"Tags[]\",\"key\":\"K\",\"value\":\"V\","
|
||||
+ "\"resourceType\":\"ResourceType\"}"));
|
||||
assertThrows(IllegalStateException.class, () -> parse("{\"operations\":{\"a:B\":{\"tagging\":[\"a:T\"],"
|
||||
+ "\"tags\":[{\"member\":\"Specs[].Tags[]\",\"key\":\"K\",\"value\":\"V\",\"resourceType\":\"Type\"}]}}}"));
|
||||
assertThrows(IllegalStateException.class, () -> parse("{\"resourceArns\":{\"a\":{\"thing\":\"*\"}},"
|
||||
+ "\"operations\":{\"a:B\":{\"tagging\":[\"a:T\"],\"tags\":[{\"member\":\"Tags{}\"}]}}}"));
|
||||
}
|
||||
|
||||
@TestFactory
|
||||
Stream<DynamicTest> everyMemberOfTheTableIsReadFromAJsonBody() {
|
||||
return TagOnCreateMembers.table().entries().entrySet().stream()
|
||||
.flatMap(operation -> operation.getValue().members().stream().map(member -> DynamicTest.dynamicTest(
|
||||
operation.getKey() + " " + member.path(), () -> assertEquals(expected(operation.getValue(), member),
|
||||
TagOnCreate.of(operation.getKey(), json(body(member).toString()))))));
|
||||
}
|
||||
|
||||
/** Each member a form can carry, as the SDK sends it. */
|
||||
@TestFactory
|
||||
Stream<DynamicTest> everyMemberOfTheTableAQueryRequestCanCarryIsReadFromItsForm() {
|
||||
return TagOnCreateMembers.table().entries().entrySet().stream()
|
||||
.flatMap(operation -> operation.getValue().members().stream()
|
||||
.filter(Member::inForm)
|
||||
.map(member -> DynamicTest.dynamicTest(operation.getKey() + " " + member.path(),
|
||||
() -> assertEquals(expected(operation.getValue(), member),
|
||||
TagOnCreate.of(operation.getKey(), form(formBody(operation.getKey(), member)))))));
|
||||
}
|
||||
|
||||
@TestFactory
|
||||
Stream<DynamicTest> aRequestCarryingNoTagsNeedsNoTaggingAction() {
|
||||
return TagOnCreateMembers.table().entries().keySet().stream().map(operation -> DynamicTest.dynamicTest(
|
||||
operation, () -> assertEquals(Optional.empty(), TagOnCreate.of(operation, json("{\"Name\":\"n\"}")))));
|
||||
}
|
||||
|
||||
private static Optional<TagOnCreate.Tagging> expected(Entry entry, Member member) {
|
||||
return Optional.of(new TagOnCreate.Tagging(entry.tagging(), List.of(new TagOnCreate.TagSet(
|
||||
member.resourceType() == null ? null : "thing", Map.of("team", "blue"))), List.of(), entry.createAction(),
|
||||
entry.requestTags()));
|
||||
}
|
||||
|
||||
/**
|
||||
* A body carrying the tag {@code team=blue} at the member, as one element of each list on the way, a tag
|
||||
* specification naming the resource type {@code thing}.
|
||||
*/
|
||||
private static JsonNode body(Member member) {
|
||||
List<Step> steps = member.steps();
|
||||
Step last = steps.getLast();
|
||||
JsonNode node = last.into() == Into.MAP
|
||||
? MAPPER.createObjectNode().put("team", "blue")
|
||||
: MAPPER.createArrayNode().add(MAPPER.createObjectNode().put(member.key(), "team")
|
||||
.put(member.value(), "blue"));
|
||||
for (int i = steps.size() - 1; i >= 0; i--) {
|
||||
Step step = steps.get(i);
|
||||
if (i < steps.size() - 1 && step.into() == Into.LIST && member.resourceType() != null) {
|
||||
((ObjectNode) node).put(member.resourceType(), "thing");
|
||||
}
|
||||
JsonNode inner = i == steps.size() - 1 || step.into() == Into.NONE ? node
|
||||
: step.into() == Into.LIST ? MAPPER.createArrayNode().add(node)
|
||||
: MAPPER.createObjectNode().set("any", node);
|
||||
ObjectNode outer = MAPPER.createObjectNode();
|
||||
outer.set(step.name(), inner);
|
||||
node = outer;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* The form parameters of the tag {@code team=blue} at the member as the SDK sends them: EC2 numbers a list
|
||||
* under its name, the Query protocol under the name its shape gives elements, or {@code member}, and a map's
|
||||
* entries under {@code entry}, but SQS, whose tags go by {@code Tag.N.Key} and {@code Tag.N.Value}. A tag
|
||||
* specification names the resource type {@code thing}.
|
||||
*/
|
||||
private static String formBody(String operation, Member member) {
|
||||
boolean ec2 = operation.startsWith("ec2:");
|
||||
boolean sqs = operation.startsWith("sqs:");
|
||||
List<String> parts = new ArrayList<>();
|
||||
String specification = null;
|
||||
for (Step step : member.querySteps()) {
|
||||
parts.add(step.name());
|
||||
if (step.into() == Into.LIST && !ec2) {
|
||||
parts.add(step.key().isEmpty() ? "member" : step.key());
|
||||
} else if (step.into() == Into.MAP && !sqs) {
|
||||
parts.add("entry");
|
||||
}
|
||||
parts.add("1");
|
||||
if (specification == null && member.resourceType() != null) {
|
||||
specification = String.join(".", parts) + "." + member.resourceType() + "=thing&";
|
||||
}
|
||||
}
|
||||
String prefix = String.join(".", parts);
|
||||
String key = member.key() != null ? member.key() : sqs ? "Key" : "key";
|
||||
String value = member.value() != null ? member.value() : sqs ? "Value" : "value";
|
||||
return (specification == null ? "" : specification) + prefix + "." + key + "=team&" + prefix + "." + value + "=blue";
|
||||
}
|
||||
|
||||
private static Member member(String member) {
|
||||
try {
|
||||
return parse("{\"resourceArns\":{\"a\":{\"thing\":\"arn:${Partition}:a:${Region}:${Account}:thing/*\"}},"
|
||||
+ "\"operations\":{\"a:B\":{\"tagging\":[\"a:TagResource\"],\"tags\":[" + member + "]}}}")
|
||||
.entries().get("a:B").members().get(0);
|
||||
} catch (IllegalStateException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static TagOnCreateMembers.Table parse(String document) throws Exception {
|
||||
return TagOnCreateMembers.parse(new ByteArrayInputStream(document.getBytes(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.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 operations the Service Reference lists with a tagging action is one
|
||||
* the vendored tag-on-create table reads, or one it names as not read yet, so a service Floci adds does not
|
||||
* tag what it creates unchecked.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class TagOnCreateNamespacesIntegrationTest {
|
||||
|
||||
@Inject
|
||||
ResolvedServiceCatalog catalog;
|
||||
|
||||
@Test
|
||||
void everyNamespaceFlociServesThatTagsOnCreationIsReadOrNamedAsNotReadYet() {
|
||||
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(TagOnCreateMembers.table().otherNamespaces());
|
||||
assertEquals(Set.of(), unread, "add these to NAMESPACES or NOT_COVERED in tools/aws/regen_iam_tag_on_create.py");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
|
||||
import io.github.hectorvent.floci.core.common.TagOnCreate.TagSet;
|
||||
import io.github.hectorvent.floci.core.common.TagOnCreate.Tagging;
|
||||
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 java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
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;
|
||||
|
||||
/** How {@link TagOnCreate} reads the tags a request carries and the condition keys it checks them with. */
|
||||
class TagOnCreateTest {
|
||||
|
||||
@Test
|
||||
void aFormsTagsAreReadFromOneToTheFirstNumberWithNoKey() {
|
||||
assertEquals(List.of(set(Map.of("a", "1", "b", "2"))), sets("sns:CreateTopic", form("Name=t"
|
||||
+ "&Tags.member.2.Key=b&Tags.member.2.Value=2&Tags.member.1.Key=a&Tags.member.1.Value=1"
|
||||
+ "&Tags.member.4.Key=d&Tags.member.4.Value=4")));
|
||||
assertEquals(List.of("a", "b"), sets("sns:CreateTopic", form("Name=t&Tags.member.1.Key=a&Tags.member.2.Key=b"))
|
||||
.getFirst().tags().keySet().stream().toList());
|
||||
// SNS's handler and SQS's stop where the number is missing, so a tag past the gap is not one the queue
|
||||
// gets, though the tagging action is still checked for it.
|
||||
assertEquals(List.of(), sets("sqs:CreateQueue", form("Action=CreateQueue&QueueName=q&Tag.2.Key=team&Tag.2.Value=blue")));
|
||||
assertEquals(List.of(set(Map.of("team", "blue"))), TagOnCreate.of("sqs:CreateQueue",
|
||||
form("Action=CreateQueue&QueueName=q&Tag.2.Key=team&Tag.2.Value=blue")).orElseThrow().otherSpellings());
|
||||
assertEquals(List.of(set(Map.of("team", ""))), TagOnCreate.of("sns:CreateTopic",
|
||||
form("Name=t&Tags.member.99999999999999999999.Key=team")).orElseThrow().checked());
|
||||
}
|
||||
|
||||
/**
|
||||
* A handler reads the SDK's own spelling, so a tag under another is not one the resource gets; the tagging
|
||||
* action is still checked for it, as another handler might apply it.
|
||||
*/
|
||||
@Test
|
||||
void aTagUnderASpellingTheHandlerDoesNotReadIsCheckedOnlyOnTheTaggingAction() {
|
||||
Tagging bare = TagOnCreate.of("sns:CreateTopic", form("Name=t&Tags.1.Key=team&Tags.1.Value=b")).orElseThrow();
|
||||
assertEquals(List.of(), bare.sets());
|
||||
assertEquals(List.of(set(Map.of("team", "b"))), bare.otherSpellings());
|
||||
// The own action is checked with no tags, as the handler applies none, and with the other spelling's.
|
||||
assertEquals(List.of(Map.of(), Map.of("aws:RequestTag/team", List.of("b"), "aws:TagKeys", List.of("team"))),
|
||||
TagOnCreate.requestTagContexts(bare));
|
||||
assertEquals(List.of(set(Map.of("team", "b"))), TagOnCreate.of("sns:CreateTopic",
|
||||
form("Name=t&TAGS.Tag.1.key=team&Tags.Tag.1.VALUE=b")).orElseThrow().otherSpellings());
|
||||
assertEquals(List.of(new TagSet("instance", Map.of("team", ""))), TagOnCreate.of("ec2:RunInstances",
|
||||
form("Action=RunInstances&TagSpecification.item.1.ResourceType=instance"
|
||||
+ "&TagSpecification.item.1.Tag.1.Key=team")).orElseThrow().otherSpellings());
|
||||
}
|
||||
|
||||
/**
|
||||
* CodeDeploy's handler reads a tag as {@code Key} and {@code Value}, or as {@code key} and {@code value}, so both
|
||||
* are the tags it applies; under any other case a tag is checked on the tagging action only.
|
||||
*/
|
||||
@Test
|
||||
void aBodysTagsAreReadInTheCasesTheirHandlerReadsAndCheckedOnTheTaggingActionInAnyOther() {
|
||||
for (String tag : List.of("{\"key\":\"team\",\"value\":\"red\"}", "{\"Key\":\"team\",\"Value\":\"red\"}")) {
|
||||
Tagging tagging = TagOnCreate.of("codedeploy:CreateApplication", json(
|
||||
"{\"applicationName\":\"demo\",\"tags\":[" + tag + "]}")).orElseThrow();
|
||||
assertEquals(List.of(set(Map.of("team", "red"))), tagging.sets(), tag);
|
||||
assertEquals(List.of(), tagging.otherSpellings(), tag);
|
||||
}
|
||||
// Under any other case the handler reads neither, and keeps an empty tag; the tagging action is checked for both.
|
||||
Tagging upper = TagOnCreate.of("codedeploy:CreateApplication", json(
|
||||
"{\"applicationName\":\"demo\",\"tags\":[{\"KEY\":\"team\",\"VALUE\":\"red\"}]}")).orElseThrow();
|
||||
assertEquals(List.of(set(Map.of("", ""))), upper.sets());
|
||||
assertEquals(List.of(set(Map.of("", "")), set(Map.of("team", "red"))), upper.checked());
|
||||
// Only CodeDeploy's handler reads a lowercase key where the SDK sends Key.
|
||||
assertEquals(List.of(), sets("dynamodb:CreateTable", json(
|
||||
"{\"TableName\":\"t\",\"Tags\":[{\"key\":\"team\",\"value\":\"red\"}]}")));
|
||||
}
|
||||
|
||||
/**
|
||||
* CodeDeploy's handler iterates its tags member whatever it holds, so an object's values are tags too; a deny on
|
||||
* one holds on the own action and the tagging action alike.
|
||||
*/
|
||||
@Test
|
||||
void anObjectsValuesAreTagsWhereTheHandlerIteratesIt() {
|
||||
Tagging object = TagOnCreate.of("codedeploy:CreateApplication", json("{\"applicationName\":\"demo\","
|
||||
+ "\"tags\":{\"0\":{\"key\":\"team\",\"value\":\"red\"}}}")).orElseThrow();
|
||||
assertEquals(List.of(set(Map.of("team", "red"))), object.sets());
|
||||
assertEquals(List.of("red"), TagOnCreate.requestTagContexts(object).getFirst().get("aws:RequestTag/team"));
|
||||
// Elsewhere it is checked on the tagging action and with the own action, beside no tags.
|
||||
Tagging elsewhere = TagOnCreate.of("dynamodb:CreateTable", json("{\"TableName\":\"t\","
|
||||
+ "\"Tags\":{\"0\":{\"Key\":\"team\",\"Value\":\"red\"}}}")).orElseThrow();
|
||||
assertEquals(List.of(), elsewhere.sets());
|
||||
assertEquals("red", elsewhere.otherSpellings().getFirst().tags().get("team"));
|
||||
assertEquals(List.of(), TagOnCreate.requestTagContexts(elsewhere).getFirst().keySet().stream().toList());
|
||||
// A map's string values are its own, not elements.
|
||||
assertEquals(List.of(), TagOnCreate.of("sqs:CreateQueue", json("{\"QueueName\":\"q\",\"tags\":{\"team\":\"blue\"}}"))
|
||||
.orElseThrow().otherSpellings());
|
||||
}
|
||||
|
||||
/**
|
||||
* CodeDeploy's handler reads a tag's key and value as text whatever they hold, a missing key as an empty one,
|
||||
* and so does the check; other handlers' keys are read as text when they are a number or a flag too.
|
||||
*/
|
||||
@Test
|
||||
void aTagKeyThatIsNoStringIsReadAsText() {
|
||||
assertEquals(List.of(set(Map.of("123", "red"))), sets("codedeploy:CreateApplication", json(
|
||||
"{\"applicationName\":\"demo\",\"tags\":[{\"key\":123,\"value\":\"red\"}]}")));
|
||||
assertEquals(List.of(set(Map.of("", "red"))), sets("codedeploy:CreateApplication", json(
|
||||
"{\"applicationName\":\"demo\",\"tags\":[{\"value\":\"red\"}]}")));
|
||||
assertEquals(List.of(set(Map.of("true", "1"))), sets("dynamodb:CreateTable", json(
|
||||
"{\"TableName\":\"t\",\"Tags\":[{\"Key\":true,\"Value\":1}]}")));
|
||||
// Under any other spelling, every element of a tag list is checked on the tagging action.
|
||||
assertEquals(List.of(set(Map.of("", ""))), TagOnCreate.of("dynamodb:CreateTable", json(
|
||||
"{\"TableName\":\"t\",\"Tags\":[{\"Key\":{}}]}")).orElseThrow().checked());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTagWithNoValueIsReadWithAnEmptyOneAndAKeyGivenTwiceKeepsItsLastValue() {
|
||||
assertEquals(List.of(set(Map.of("team", ""))), sets("sns:CreateTopic", form("Name=t&Tags.member.1.Key=team")));
|
||||
assertEquals(List.of(set(Map.of("team", "red", "env", ""))), sets("dynamodb:CreateTable", json(
|
||||
"{\"TableName\":\"t\",\"Tags\":[{\"Key\":\"team\",\"Value\":\"blue\"},{\"Key\":\"env\"},"
|
||||
+ "{\"Key\":\"team\",\"Value\":\"red\"}]}")));
|
||||
// A value with no key tags nothing.
|
||||
assertEquals(Optional.empty(), TagOnCreate.of("sns:CreateTopic", form("Name=t&Tags.member.1.Value=v")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sqsTagsAreReadAsTheJsonProtocolsMapAndTheQueryProtocolsTagParameters() {
|
||||
Tagging json = TagOnCreate.of("sqs:CreateQueue", json("{\"QueueName\":\"q\",\"tags\":{\"team\":\"blue\"}}"))
|
||||
.orElseThrow();
|
||||
assertEquals(new Tagging("sqs:TagQueue", List.of(set(Map.of("team", "blue"))), List.of(), false, true), json);
|
||||
assertEquals(json, TagOnCreate.of("sqs:CreateQueue",
|
||||
form("Action=CreateQueue&QueueName=q&Tag.1.Key=team&Tag.1.Value=blue")).orElseThrow());
|
||||
}
|
||||
|
||||
/**
|
||||
* Each resource type an EC2 request names gets its own specifications' tags, as {@code Ec2QueryHandler}
|
||||
* applies them, so one type's tags cannot stand in for another's.
|
||||
*/
|
||||
@Test
|
||||
void anEc2RequestsTagsAreReadByTheResourceTypeEachSpecificationNames() {
|
||||
Tagging tagging = TagOnCreate.of("ec2:RunInstances", form("Action=RunInstances&ImageId=ami-1"
|
||||
+ "&TagSpecification.1.ResourceType=instance&TagSpecification.1.Tag.1.Key=team"
|
||||
+ "&TagSpecification.1.Tag.1.Value=red&TagSpecification.2.ResourceType=volume"
|
||||
+ "&TagSpecification.2.Tag.1.Key=team&TagSpecification.2.Tag.1.Value=blue"
|
||||
+ "&TagSpecifications.1.ResourceType=instance&TagSpecifications.1.Tag.1.Key=env"
|
||||
+ "&TagSpecifications.1.Tag.1.Value=dev")).orElseThrow();
|
||||
assertEquals(new Tagging("ec2:CreateTags", List.of(new TagSet("instance", Map.of("team", "red", "env", "dev")),
|
||||
new TagSet("volume", Map.of("team", "blue"))), List.of(), true, true), tagging);
|
||||
Map<String, List<String>> context = TagOnCreate.conditionContext(tagging, tagging.sets().getFirst(),
|
||||
"ec2:RunInstances");
|
||||
assertEquals(List.of("RunInstances"), context.get("ec2:CreateAction"));
|
||||
assertEquals(List.of("red"), context.get("aws:RequestTag/team"));
|
||||
assertEquals(List.of("team", "env"), context.get("aws:TagKeys"));
|
||||
}
|
||||
|
||||
/** {@code Ec2QueryHandler} stops at the first tag specification that names no resource type. */
|
||||
@Test
|
||||
void anEc2RequestsSpecificationsAreReadToTheFirstWithNoResourceType() {
|
||||
assertEquals(List.of(new TagSet("instance", Map.of("a", "1"))), sets("ec2:RunInstances", form(
|
||||
"Action=RunInstances&TagSpecification.1.ResourceType=instance&TagSpecification.1.Tag.1.Key=a"
|
||||
+ "&TagSpecification.1.Tag.1.Value=1&TagSpecification.2.Tag.1.Key=b"
|
||||
+ "&TagSpecification.3.ResourceType=volume&TagSpecification.3.Tag.1.Key=c")));
|
||||
}
|
||||
|
||||
/** A tag specification's tags are checked on the resource it names, its name not known yet. */
|
||||
@Test
|
||||
void aSpecificationsTagsGoToTheResourceOfItsTypeAndOtherTagsToTheOperationsResources() {
|
||||
List<String> checked = List.of("*");
|
||||
assertEquals(List.of("arn:aws:ec2:us-east-1:000000000000:instance/*"), TagOnCreate.resources("ec2:RunInstances",
|
||||
new TagSet("instance", Map.of()), "aws", "us-east-1", "000000000000", checked));
|
||||
assertEquals(List.of("arn:aws-cn:ec2:cn-north-1::image/*"), TagOnCreate.resources("ec2:CreateImage",
|
||||
new TagSet("image", Map.of()), "aws-cn", "cn-north-1", "000000000000", checked));
|
||||
assertEquals(checked, TagOnCreate.resources("ec2:RunInstances", new TagSet("no-such-type", Map.of()),
|
||||
"aws", "us-east-1", "000000000000", checked));
|
||||
assertEquals(checked, TagOnCreate.resources("sns:CreateTopic", new TagSet(null, Map.of()),
|
||||
"aws", "us-east-1", "000000000000", checked));
|
||||
}
|
||||
|
||||
/**
|
||||
* RDS, DocumentDB and Neptune read three spellings, the first two in either order, so a key given under both
|
||||
* with two values may end up with either, and each is checked.
|
||||
*/
|
||||
@Test
|
||||
void rdsTagsAreReadUnderEachSpellingItsHandlersRead() {
|
||||
assertEquals(List.of(set(Map.of("a", "1", "b", "2", "c", "3"))), sets("rds:CreateDBParameterGroup", form(
|
||||
"Tags.member.1.Key=a&Tags.member.1.Value=1&Tags.Tag.1.Key=b&Tags.Tag.1.Value=2&Tag.1.Key=c&Tag.1.Value=3")));
|
||||
assertEquals(List.of(set(Map.of("team", "blue")), set(Map.of("team", "red"))), sets("rds:CreateDBParameterGroup",
|
||||
form("Tags.member.1.Key=team&Tags.member.1.Value=red&Tags.Tag.1.Key=team&Tags.Tag.1.Value=blue")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void elastiCacheAndRedshiftTagsAreReadAsTheirHandlersNumberThem() {
|
||||
// ElastiCacheServerlessQueryHandler takes either spelling at each number.
|
||||
assertEquals(List.of(set(Map.of("a", "1", "b", "2"))), sets("elasticache:CreateServerlessCache",
|
||||
form("Tags.Tag.1.Key=a&Tags.Tag.1.Value=1&Tags.member.2.Key=b&Tags.member.2.Value=2")));
|
||||
// ElastiCacheQueryHandler reads each spelling from 1.
|
||||
assertEquals(List.of(set(Map.of("a", "1"))), sets("elasticache:CreateCacheCluster",
|
||||
form("Tags.Tag.1.Key=a&Tags.Tag.1.Value=1&Tags.member.2.Key=b&Tags.member.2.Value=2")));
|
||||
// RedshiftQueryHandler reads every number of an integration's tags, but a blank key.
|
||||
assertEquals(List.of(set(Map.of("a", "1", "b", "2"))), sets("redshift:CreateIntegration",
|
||||
form("TagList.Tag.3.Key=a&TagList.Tag.3.Value=1&TagList.Tag.7.Key=b&TagList.Tag.7.Value=2"
|
||||
+ "&TagList.Tag.8.Key=%20")));
|
||||
}
|
||||
|
||||
/** CloudWatch's handler reads an alarm's tags from {@code tags} too; other handlers read the member's name only. */
|
||||
@Test
|
||||
void aBodysMemberIsReadUnderItsOwnNameAndAnAlarmsUnderTagsToo() {
|
||||
assertEquals(List.of(set(Map.of("team", "blue"))), sets("cloudwatch:PutMetricAlarm", json(
|
||||
"{\"AlarmName\":\"a\",\"tags\":[{\"Key\":\"team\",\"Value\":\"blue\"}]}")));
|
||||
assertEquals(List.of(set(Map.of("team", "red"))), sets("cloudwatch:PutCompositeAlarm", json(
|
||||
"{\"AlarmName\":\"a\",\"Tags\":[{\"Key\":\"team\",\"Value\":\"red\"}],"
|
||||
+ "\"tags\":[{\"Key\":\"team\",\"Value\":\"blue\"}]}")));
|
||||
Tagging lower = TagOnCreate.of("dynamodb:CreateTable", json(
|
||||
"{\"TableName\":\"t\",\"tags\":[{\"Key\":\"team\",\"Value\":\"blue\"}]}")).orElseThrow();
|
||||
assertEquals(List.of(), lower.sets());
|
||||
assertEquals(List.of(set(Map.of("team", "blue"))), lower.otherSpellings());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCborBodysTagsAreRead() throws Exception {
|
||||
byte[] body = new ObjectMapper(new CBORFactory()).writeValueAsBytes(Map.of("AlarmName", "a",
|
||||
"Tags", List.of(Map.of("Key", "team", "Value", "blue"))));
|
||||
Tagging tagging = TagOnCreate.of("cloudwatch:PutMetricAlarm", request("application/cbor", body)).orElseThrow();
|
||||
assertEquals(new Tagging("cloudwatch:TagResource", List.of(set(Map.of("team", "blue"))), List.of(), false, true),
|
||||
tagging);
|
||||
assertFalse(TagOnCreate.conditionContext(tagging, tagging.sets().getFirst(), "cloudwatch:PutMetricAlarm")
|
||||
.keySet().stream().anyMatch(key -> key.endsWith(":CreateAction")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOperationsOwnActionTakesEachSetOfTagsOnlyWhereTheServiceReferenceSaysItDoes() {
|
||||
Tagging queue = TagOnCreate.of("sqs:CreateQueue", json("{\"QueueName\":\"q\",\"tags\":{\"team\":\"blue\"}}"))
|
||||
.orElseThrow();
|
||||
assertEquals(List.of(Map.of("aws:RequestTag/team", List.of("blue"), "aws:TagKeys", List.of("team"))),
|
||||
TagOnCreate.requestTagContexts(queue));
|
||||
// RDS lists aws:RequestTag for neither ModifyDBInstance nor its resources, only for the tagging action.
|
||||
assertFalse(TagOnCreate.of("rds:ModifyDBInstance", form("Action=ModifyDBInstance&DBInstanceIdentifier=d"
|
||||
+ "&TagSpecifications.item.1.ResourceType=auto-backup&TagSpecifications.item.1.Tags.Tag.1.Key=team"
|
||||
+ "&TagSpecifications.item.1.Tags.Tag.1.Value=blue")).orElseThrow().requestTags());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOperationTheTableDoesNotReadOrChecksByHandNeedsNothingHere() {
|
||||
assertEquals(Optional.empty(), TagOnCreate.of("sqs:SendMessage", json("{\"tags\":{\"a\":\"b\"}}")));
|
||||
assertEquals(Optional.empty(), TagOnCreate.of("logs:CreateLogGroup", json(
|
||||
"{\"logGroupName\":\"g\",\"tags\":{\"a\":\"b\"}}")));
|
||||
assertEquals(Optional.empty(), TagOnCreate.of("dynamodb:CreateTable", json("{\"Tags\":[]}")));
|
||||
// A tags member of the other shape is none the handler reads, though the tagging action is checked for it.
|
||||
assertEquals(List.of(), sets("dynamodb:CreateTable", json("{\"Tags\":{\"a\":\"b\"}}")));
|
||||
}
|
||||
|
||||
private static TagSet set(Map<String, String> tags) {
|
||||
return new TagSet(null, tags);
|
||||
}
|
||||
|
||||
/** The sets of tags the request carries as its handler reads them. */
|
||||
private static List<TagSet> sets(String operation, ContainerRequestContext request) {
|
||||
return TagOnCreate.of(operation, request).orElseThrow().sets();
|
||||
}
|
||||
|
||||
private static ContainerRequestContext json(String body) {
|
||||
return request("application/x-amz-json-1.1", body.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static ContainerRequestContext form(String body) {
|
||||
return request("application/x-www-form-urlencoded", body.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static ContainerRequestContext request(String mediaType, byte[] bytes) {
|
||||
ContainerRequestContext request = mock(ContainerRequestContext.class);
|
||||
when(request.getMediaType()).thenReturn(MediaType.valueOf(mediaType));
|
||||
when(request.getEntityStream()).thenAnswer(invocation -> new ByteArrayInputStream(bytes));
|
||||
return request;
|
||||
}
|
||||
}
|
||||
+502
@@ -0,0 +1,502 @@
|
||||
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.Response;
|
||||
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.List;
|
||||
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.assertTrue;
|
||||
|
||||
/**
|
||||
* A request that tags the resource it creates also needs the service's tagging action, as AWS checks it: the
|
||||
* SNS API reference has "To be able to tag a topic on creation, you must have the {@code sns:CreateTopic}
|
||||
* and {@code sns:TagResource} permissions." Without it a caller allowed to create but not to tag could set
|
||||
* the tags a tag-based policy trusts.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class IamTagOnCreateEnforcementIntegrationTest {
|
||||
|
||||
private static final String ADMIN = "test";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String IMAGE = "ami-0abcdef1234567890";
|
||||
private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory());
|
||||
|
||||
@TestHTTPResource("/")
|
||||
static URI baseUri;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aQueueCreatedWithTagsNeedsTagQueueOverEitherProtocol() {
|
||||
User user = user("tag-queue");
|
||||
String queue = "tag-queue-" + suffix();
|
||||
|
||||
// A queue created without tags needs only its own action.
|
||||
user.policy(allow("sqs:CreateQueue"));
|
||||
deleteQueueLater(user.query("sqs", "CreateQueue").formParam("QueueName", queue + "-plain").post("/"));
|
||||
refused(user.query("sqs", "CreateQueue").formParam("QueueName", queue)
|
||||
.formParam("Tag.1.Key", "team").formParam("Tag.1.Value", "blue").post("/").then(), "sqs:TagQueue");
|
||||
refusedJson(user.json("sqs", "AmazonSQS.CreateQueue", "1.0")
|
||||
.body("{\"QueueName\":\"" + queue + "\",\"tags\":{\"team\":\"blue\"}}").post("/").then(), "sqs:TagQueue");
|
||||
|
||||
// Allowed to create but not to tag, the caller is refused the create, not the tagging.
|
||||
user.policy(allow("sqs:TagQueue"));
|
||||
refused(user.query("sqs", "CreateQueue").formParam("QueueName", queue)
|
||||
.formParam("Tag.1.Key", "team").formParam("Tag.1.Value", "blue").post("/").then(), "sqs:CreateQueue");
|
||||
|
||||
user.policy(allow("sqs:CreateQueue") + "," + allow("sqs:TagQueue"));
|
||||
deleteQueueLater(user.query("sqs", "CreateQueue").formParam("QueueName", queue)
|
||||
.formParam("Tag.1.Key", "team").formParam("Tag.1.Value", "blue").post("/"));
|
||||
}
|
||||
|
||||
/** The create's own action sees the tags too, as the Service Reference lists the keys for it. */
|
||||
@Test
|
||||
void theCreatesOwnActionIsCheckedWithTheTagsItCarries() {
|
||||
User user = user("tag-create-condition");
|
||||
String queue = "tag-condition-" + suffix();
|
||||
user.policy("{\"Effect\":\"Allow\",\"Action\":\"sqs:CreateQueue\",\"Resource\":\"*\","
|
||||
+ "\"Condition\":{\"StringEquals\":{\"aws:RequestTag/team\":\"blue\"}}}," + allow("sqs:TagQueue"));
|
||||
refused(createQueue(user, queue, "red").then(), "sqs:CreateQueue");
|
||||
refused(user.query("sqs", "CreateQueue").formParam("QueueName", queue).post("/").then(), "sqs:CreateQueue");
|
||||
refusedJson(user.json("sqs", "AmazonSQS.CreateQueue", "1.0")
|
||||
.body("{\"QueueName\":\"" + queue + "\",\"tags\":{\"team\":\"red\"}}").post("/").then(), "sqs:CreateQueue");
|
||||
deleteQueueLater(createQueue(user, queue, "blue"));
|
||||
|
||||
// The usual guard: no create without the tag. It must not refuse a create that carries it.
|
||||
user.policy(allow("sqs:CreateQueue") + "," + allow("sqs:TagQueue") + ",{\"Effect\":\"Deny\","
|
||||
+ "\"Action\":\"sqs:CreateQueue\",\"Resource\":\"*\",\"Condition\":{\"Null\":{\"aws:RequestTag/team\":\"true\"}}}");
|
||||
refused(user.query("sqs", "CreateQueue").formParam("QueueName", queue + "-untagged").post("/").then(),
|
||||
"sqs:CreateQueue");
|
||||
deleteQueueLater(createQueue(user, queue + "-guarded", "blue"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Only an action the Service Reference gives the request's tags to sees them: Cognito's
|
||||
* {@code CreateIdentityPool} does, {@code UpdateIdentityPool} does not, though both carry them.
|
||||
*/
|
||||
@Test
|
||||
void anActionTheServiceReferenceGivesNoRequestTagsIsCheckedWithout() {
|
||||
User user = user("tag-pool");
|
||||
String pool = "tag_pool_" + suffix();
|
||||
String created = admin("cognito-identity").header("X-Amz-Target", "AWSCognitoIdentityService.CreateIdentityPool")
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body("{\"IdentityPoolName\":\"" + pool + "\",\"AllowUnauthenticatedIdentities\":false}")
|
||||
.post("/").then().statusCode(200).extract().path("IdentityPoolId");
|
||||
cleanup.register(() -> admin("cognito-identity").header("X-Amz-Target", "AWSCognitoIdentityService.DeleteIdentityPool")
|
||||
.contentType("application/x-amz-json-1.1").body("{\"IdentityPoolId\":\"" + created + "\"}").post("/"));
|
||||
user.policy(allow("cognito-identity:CreateIdentityPool") + "," + allow("cognito-identity:UpdateIdentityPool") + ","
|
||||
+ allow("cognito-identity:TagResource") + ",{\"Effect\":\"Deny\",\"Action\":["
|
||||
+ "\"cognito-identity:CreateIdentityPool\",\"cognito-identity:UpdateIdentityPool\"],\"Resource\":\"*\","
|
||||
+ "\"Condition\":{\"ForAnyValue:StringEquals\":{\"aws:TagKeys\":[\"env\"]}}}");
|
||||
|
||||
refusedJson(user.json("cognito-identity", "AWSCognitoIdentityService.CreateIdentityPool", "1.1")
|
||||
.body("{\"IdentityPoolName\":\"" + pool + "_new\",\"AllowUnauthenticatedIdentities\":false,"
|
||||
+ "\"IdentityPoolTags\":{\"env\":\"dev\"}}").post("/").then(), "cognito-identity:CreateIdentityPool");
|
||||
user.json("cognito-identity", "AWSCognitoIdentityService.UpdateIdentityPool", "1.1")
|
||||
.body("{\"IdentityPoolId\":\"" + created + "\",\"IdentityPoolName\":\"" + pool + "\","
|
||||
+ "\"AllowUnauthenticatedIdentities\":false,\"IdentityPoolTags\":{\"env\":\"dev\"}}")
|
||||
.post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTaggingActionIsCheckedWithTheTagsTheRequestCarries() {
|
||||
User user = user("tag-topic");
|
||||
String topic = "tag-topic-" + suffix();
|
||||
user.policy(allow("sns:CreateTopic") + ",{\"Effect\":\"Allow\",\"Action\":\"sns:TagResource\",\"Resource\":\"*\","
|
||||
+ "\"Condition\":{\"StringEquals\":{\"aws:RequestTag/team\":\"blue\"},"
|
||||
+ "\"ForAllValues:StringEquals\":{\"aws:TagKeys\":[\"team\"]}}}");
|
||||
|
||||
refused(createTopic(user, topic, Map.of("team", "red")), "sns:TagResource");
|
||||
refused(createTopic(user, topic, Map.of("team", "blue", "env", "dev")), "sns:TagResource");
|
||||
createTopic(user, topic, Map.of("team", "blue")).statusCode(200);
|
||||
cleanup.register(() -> admin("sns").formParam("Action", "DeleteTopic")
|
||||
.formParam("TopicArn", "arn:aws:sns:us-east-1:" + ACCOUNT + ":" + topic).post("/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aJsonRequestsTagsNeedTheTaggingAction() {
|
||||
User user = user("tag-json");
|
||||
String table = "tag-table-" + suffix();
|
||||
String createTable = """
|
||||
{"TableName":"%s","BillingMode":"PAY_PER_REQUEST",
|
||||
"AttributeDefinitions":[{"AttributeName":"id","AttributeType":"S"}],
|
||||
"KeySchema":[{"AttributeName":"id","KeyType":"HASH"}],
|
||||
"Tags":[{"Key":"team","Value":"blue"}]}""".formatted(table);
|
||||
String createKey = "{\"Tags\":[{\"TagKey\":\"team\",\"TagValue\":\"blue\"}]}";
|
||||
|
||||
user.policy(allow("dynamodb:CreateTable") + "," + allow("kms:CreateKey"));
|
||||
refusedJson(user.json("dynamodb", "DynamoDB_20120810.CreateTable", "1.0").body(createTable).post("/").then(),
|
||||
"dynamodb:TagResource");
|
||||
refusedJson(user.json("kms", "TrentService.CreateKey", "1.1").body(createKey).post("/").then(),
|
||||
"kms:TagResource");
|
||||
|
||||
user.policy(allow("dynamodb:CreateTable") + "," + allow("dynamodb:TagResource") + ","
|
||||
+ allow("kms:CreateKey") + "," + allow("kms:TagResource"));
|
||||
user.json("dynamodb", "DynamoDB_20120810.CreateTable", "1.0").body(createTable).post("/").then().statusCode(200);
|
||||
cleanup.register(() -> admin("dynamodb").header("X-Amz-Target", "DynamoDB_20120810.DeleteTable")
|
||||
.contentType("application/x-amz-json-1.0").body("{\"TableName\":\"" + table + "\"}").post("/"));
|
||||
user.json("kms", "TrentService.CreateKey", "1.1").body(createKey).post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* The tagging action is found by the operation, not by the action it is authorized as: Budgets'
|
||||
* {@code CreateBudget} is authorized as {@code budgets:ModifyBudget}.
|
||||
*/
|
||||
@Test
|
||||
void aBudgetCreatedWithTagsNeedsTagResourceThoughItIsAuthorizedAsModifyBudget() {
|
||||
User user = user("tag-budget");
|
||||
String budget = "tag-budget-" + suffix();
|
||||
String create = """
|
||||
{"AccountId":"%s","Budget":{"BudgetName":"%s","BudgetType":"COST","TimeUnit":"MONTHLY",
|
||||
"BudgetLimit":{"Amount":"100","Unit":"USD"}},"ResourceTags":[{"Key":"team","Value":"blue"}]}"""
|
||||
.formatted(ACCOUNT, budget);
|
||||
String modify = allow("budgets:ModifyBudget");
|
||||
|
||||
user.policy(modify);
|
||||
refusedJson(user.json("budgets", "AWSBudgetServiceGateway.CreateBudget", "1.1").body(create).post("/").then(),
|
||||
"budgets:TagResource");
|
||||
|
||||
user.policy(modify + "," + allow("budgets:TagResource"));
|
||||
user.json("budgets", "AWSBudgetServiceGateway.CreateBudget", "1.1").body(create).post("/").then()
|
||||
.statusCode(200);
|
||||
cleanup.register(() -> admin("budgets").header("X-Amz-Target", "AWSBudgetServiceGateway.DeleteBudget")
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body("{\"AccountId\":\"" + ACCOUNT + "\",\"BudgetName\":\"" + budget + "\"}").post("/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInstanceLaunchedWithTagsNeedsCreateTagsForRunInstances() {
|
||||
User user = user("tag-instance");
|
||||
// The tagging permission is scoped to the action that creates the resource, as EC2's examples scope it.
|
||||
user.policy(allow("ec2:RunInstances") + "," + createTagsFor("CreateVolume"));
|
||||
refused(runInstances(user).then(), "ec2:CreateTags");
|
||||
|
||||
user.policy(allow("ec2:RunInstances") + "," + createTagsFor("RunInstances"));
|
||||
terminateLater(runInstances(user));
|
||||
}
|
||||
|
||||
/**
|
||||
* EC2 checks {@code ec2:CreateTags} on each resource a tag specification names, as its examples scope the grant,
|
||||
* so one scoped to instances covers an instance's tags and not a volume's.
|
||||
*/
|
||||
@Test
|
||||
void anInstancesTagsAreCheckedOnTheInstanceAndAVolumesOnTheVolume() {
|
||||
User user = user("tag-instance-scoped");
|
||||
user.policy(allow("ec2:RunInstances") + ",{\"Effect\":\"Allow\",\"Action\":\"ec2:CreateTags\","
|
||||
+ "\"Resource\":\"arn:aws:ec2:us-east-1:" + ACCOUNT + ":instance/*\","
|
||||
+ "\"Condition\":{\"StringEquals\":{\"ec2:CreateAction\":\"RunInstances\"}}}");
|
||||
terminateLater(runInstances(user, "instance", "blue"));
|
||||
refused(runInstances(user, "instance", "blue", "volume", "blue").then(), "ec2:CreateTags");
|
||||
}
|
||||
|
||||
/** Each resource type's tags are checked apart, so a volume's cannot stand in for an instance's. */
|
||||
@Test
|
||||
void eachResourceTypesTagsAreCheckedApart() {
|
||||
User user = user("tag-instance-sets");
|
||||
user.policy(allow("ec2:RunInstances") + ",{\"Effect\":\"Allow\",\"Action\":\"ec2:CreateTags\","
|
||||
+ "\"Resource\":\"*\",\"Condition\":{\"StringEquals\":{\"aws:RequestTag/team\":\"blue\"}}}");
|
||||
refused(runInstances(user, "instance", "red", "volume", "blue").then(), "ec2:CreateTags");
|
||||
terminateLater(runInstances(user, "instance", "blue", "volume", "blue"));
|
||||
}
|
||||
|
||||
/** The create's own action is checked with each resource's tags apart too. */
|
||||
@Test
|
||||
void theCreatesOwnActionIsCheckedWithEachResourcesTagsApart() {
|
||||
User user = user("tag-vpc");
|
||||
user.policy("{\"Effect\":\"Allow\",\"Action\":\"ec2:CreateVpc\",\"Resource\":\"*\","
|
||||
+ "\"Condition\":{\"StringEquals\":{\"aws:RequestTag/team\":\"blue\"}}}," + allow("ec2:CreateTags"));
|
||||
refused(createVpc(user, "vpc", "red", "vpc-flow-log", "blue").then(), "ec2:CreateVpc");
|
||||
String vpcId = createVpc(user, "vpc", "blue").then().statusCode(200).extract().path("CreateVpcResponse.vpc.vpcId");
|
||||
cleanup.register(() -> admin("ec2").formParam("Action", "DeleteVpc").formParam("VpcId", vpcId).post("/"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A tag the handler would not apply is not taken for one the resource gets: SQS's handler stops at the first
|
||||
* missing number, SNS's reads {@code Tags.member.N} only.
|
||||
*/
|
||||
@Test
|
||||
void aTagTheHandlerWouldNotApplyDoesNotMeetAPolicyRequiringIt() {
|
||||
User user = user("tag-unread");
|
||||
String name = "tag-unread-" + suffix();
|
||||
user.policy("{\"Effect\":\"Allow\",\"Action\":[\"sqs:CreateQueue\",\"sns:CreateTopic\"],\"Resource\":\"*\","
|
||||
+ "\"Condition\":{\"StringEquals\":{\"aws:RequestTag/team\":\"blue\"}}}," + allow("sqs:TagQueue") + ","
|
||||
+ allow("sns:TagResource"));
|
||||
refused(user.query("sqs", "CreateQueue").formParam("QueueName", name)
|
||||
.formParam("Tag.2.Key", "team").formParam("Tag.2.Value", "blue").post("/").then(), "sqs:CreateQueue");
|
||||
refused(user.query("sns", "CreateTopic").formParam("Name", name)
|
||||
.formParam("Tags.1.Key", "team").formParam("Tags.1.Value", "blue").post("/").then(), "sns:CreateTopic");
|
||||
deleteQueueLater(createQueue(user, name, "blue"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRoleCreatedWithTagsNeedsTagRole() {
|
||||
User user = user("tag-role");
|
||||
String role = "tag-role-" + suffix();
|
||||
String trust = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}";
|
||||
|
||||
user.policy(allow("iam:CreateRole"));
|
||||
refused(user.query("iam", "CreateRole").formParam("RoleName", role).formParam("AssumeRolePolicyDocument", trust)
|
||||
.formParam("Tags.member.1.Key", "team").formParam("Tags.member.1.Value", "blue").post("/").then(),
|
||||
"iam:TagRole");
|
||||
|
||||
user.policy(allow("iam:CreateRole") + "," + allow("iam:TagRole"));
|
||||
user.query("iam", "CreateRole").formParam("RoleName", role).formParam("AssumeRolePolicyDocument", trust)
|
||||
.formParam("Tags.member.1.Key", "team").formParam("Tags.member.1.Value", "blue").post("/").then()
|
||||
.statusCode(200);
|
||||
cleanup.register(() -> admin("iam").formParam("Action", "DeleteRole").formParam("RoleName", role).post("/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFunctionCreatedWithTagsNeedsTagResourceOverItsRestRoute() {
|
||||
String role = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", "tag-fn-" + suffix(),
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"s3:*\",\"Resource\":\"*\"}]}");
|
||||
User user = user("tag-function");
|
||||
String name = "tag-fn-" + suffix();
|
||||
String body = """
|
||||
{"FunctionName":"%s","Runtime":"nodejs20.x","Handler":"index.handler","Role":"%s",
|
||||
"Tags":{"team":"blue"}}""".formatted(name, role);
|
||||
String passRole = "{\"Effect\":\"Allow\",\"Action\":\"iam:PassRole\",\"Resource\":\"" + role + "\"}";
|
||||
|
||||
user.policy(allow("lambda:CreateFunction") + "," + passRole);
|
||||
refusedRest(user.rest("lambda").body(body).post("/2015-03-31/functions").then(), "lambda:TagResource");
|
||||
|
||||
user.policy(allow("lambda:CreateFunction") + "," + passRole + "," + allow("lambda:TagResource"));
|
||||
user.rest("lambda").body(body).post("/2015-03-31/functions").then().statusCode(201);
|
||||
cleanup.register(() -> admin("lambda").contentType("application/json")
|
||||
.delete("/2015-03-31/functions/{name}", name));
|
||||
}
|
||||
|
||||
/** A function's tags are checked on the function its body names, as its own action is. */
|
||||
@Test
|
||||
void aFunctionsTagsAreCheckedOnTheFunctionItCreates() {
|
||||
String role = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", "tag-fn-" + suffix(),
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"s3:*\",\"Resource\":\"*\"}]}");
|
||||
User user = user("tag-function-scoped");
|
||||
String name = "tag-fn-" + suffix();
|
||||
String function = "arn:aws:lambda:us-east-1:" + ACCOUNT + ":function:" + name;
|
||||
user.policy(allow("lambda:CreateFunction") + ",{\"Effect\":\"Allow\",\"Action\":\"iam:PassRole\","
|
||||
+ "\"Resource\":\"" + role + "\"},{\"Effect\":\"Allow\",\"Action\":\"lambda:TagResource\","
|
||||
+ "\"Resource\":\"" + function + "\"},{\"Effect\":\"Deny\",\"Action\":\"lambda:CreateFunction\","
|
||||
+ "\"Resource\":\"" + function + "-denied\"}");
|
||||
refusedRest(user.rest("lambda").body(function(name + "-other", role)).post("/2015-03-31/functions").then(),
|
||||
"lambda:TagResource");
|
||||
refusedRest(user.rest("lambda").body(function(name + "-denied", role)).post("/2015-03-31/functions").then(),
|
||||
"lambda:CreateFunction");
|
||||
user.rest("lambda").body(function(name, role)).post("/2015-03-31/functions").then().statusCode(201);
|
||||
cleanup.register(() -> admin("lambda").contentType("application/json")
|
||||
.delete("/2015-03-31/functions/{name}", name));
|
||||
}
|
||||
|
||||
/**
|
||||
* CodeDeploy's handler reads a tag's key and value in either case, so the tagging action is checked for both,
|
||||
* and the create's own action sees them.
|
||||
*/
|
||||
@Test
|
||||
void anApplicationsTagsInEitherCaseNeedTagResource() {
|
||||
User user = user("tag-application");
|
||||
String application = "tag-app-" + suffix();
|
||||
String create = "{\"applicationName\":\"" + application + "\",\"tags\":[{\"key\":\"team\",\"value\":\"red\"}]}";
|
||||
user.policy(allow("codedeploy:CreateApplication"));
|
||||
refusedJson(user.json("codedeploy", "CodeDeploy_20141006.CreateApplication", "1.1").body(create).post("/").then(),
|
||||
"codedeploy:TagResource");
|
||||
// The handler keeps a key that is a number as its text, so it needs the tagging action too.
|
||||
refusedJson(user.json("codedeploy", "CodeDeploy_20141006.CreateApplication", "1.1")
|
||||
.body("{\"applicationName\":\"" + application + "\",\"tags\":[{\"key\":123,\"value\":\"red\"}]}")
|
||||
.post("/").then(), "codedeploy:TagResource");
|
||||
|
||||
user.policy("{\"Effect\":\"Allow\",\"Action\":\"codedeploy:CreateApplication\",\"Resource\":\"*\","
|
||||
+ "\"Condition\":{\"StringEquals\":{\"aws:RequestTag/team\":\"red\"}}}," + allow("codedeploy:TagResource"));
|
||||
user.json("codedeploy", "CodeDeploy_20141006.CreateApplication", "1.1").body(create).post("/").then()
|
||||
.statusCode(200);
|
||||
cleanup.register(() -> admin("codedeploy").header("X-Amz-Target", "CodeDeploy_20141006.DeleteApplication")
|
||||
.contentType("application/x-amz-json-1.1").body("{\"applicationName\":\"" + application + "\"}").post("/"));
|
||||
|
||||
// The handler iterates an object's values as tags, so a deny on one holds however they are shaped.
|
||||
user.policy(allow("codedeploy:CreateApplication") + "," + allow("codedeploy:TagResource")
|
||||
+ ",{\"Effect\":\"Deny\",\"Action\":\"codedeploy:CreateApplication\",\"Resource\":\"*\","
|
||||
+ "\"Condition\":{\"StringEquals\":{\"aws:RequestTag/team\":\"red\"}}}");
|
||||
refusedJson(user.json("codedeploy", "CodeDeploy_20141006.CreateApplication", "1.1")
|
||||
.body("{\"applicationName\":\"" + application + "-object\",\"tags\":{\"0\":{\"key\":\"team\",\"value\":\"red\"}}}")
|
||||
.post("/").then(), "codedeploy:CreateApplication");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAlarmPutWithTagsOverCborNeedsTagResource() throws IOException {
|
||||
User user = user("tag-alarm");
|
||||
String alarm = "tag-alarm-" + suffix();
|
||||
byte[] body = CBOR_MAPPER.writeValueAsBytes(Map.of("AlarmName", alarm, "MetricName", "Errors",
|
||||
"Namespace", "Tag/OnCreate", "Statistic", "Sum", "Period", 60, "EvaluationPeriods", 1,
|
||||
"Threshold", 1.0, "ComparisonOperator", "GreaterThanThreshold",
|
||||
"Tags", List.of(Map.of("Key", "team", "Value", "blue"))));
|
||||
|
||||
user.policy(allow("cloudwatch:PutMetricAlarm"));
|
||||
Response denied = user.cbor("monitoring").body(body)
|
||||
.post("/service/GraniteServiceVersion20100801/operation/PutMetricAlarm");
|
||||
JsonNode error = CBOR_MAPPER.readTree(denied.then().statusCode(403).extract().asByteArray());
|
||||
assertTrue(error.path("message").asText().contains("cloudwatch:TagResource"), error.toString());
|
||||
|
||||
user.policy(allow("cloudwatch:PutMetricAlarm") + "," + allow("cloudwatch:TagResource"));
|
||||
user.cbor("monitoring").body(body).post("/service/GraniteServiceVersion20100801/operation/PutMetricAlarm")
|
||||
.then().statusCode(200);
|
||||
cleanup.register(() -> admin("monitoring").formParam("Action", "DeleteAlarms")
|
||||
.formParam("AlarmNames.member.1", alarm).post("/"));
|
||||
}
|
||||
|
||||
private static String function(String name, String role) {
|
||||
return """
|
||||
{"FunctionName":"%s","Runtime":"nodejs20.x","Handler":"index.handler","Role":"%s",
|
||||
"Tags":{"team":"blue"}}""".formatted(name, role);
|
||||
}
|
||||
|
||||
private static ValidatableResponse createTopic(User user, String name, Map<String, String> tags) {
|
||||
RequestSpecification request = user.query("sns", "CreateTopic").formParam("Name", name);
|
||||
int index = 1;
|
||||
for (Map.Entry<String, String> tag : tags.entrySet()) {
|
||||
request = request.formParam("Tags.member." + index + ".Key", tag.getKey())
|
||||
.formParam("Tags.member." + index + ".Value", tag.getValue());
|
||||
index++;
|
||||
}
|
||||
return request.post("/").then();
|
||||
}
|
||||
|
||||
private static Response createQueue(User user, String name, String team) {
|
||||
return user.query("sqs", "CreateQueue").formParam("QueueName", name)
|
||||
.formParam("Tag.1.Key", "team").formParam("Tag.1.Value", team).post("/");
|
||||
}
|
||||
|
||||
private static Response runInstances(User user) {
|
||||
return runInstances(user, "instance", "blue");
|
||||
}
|
||||
|
||||
/** An instance launched with a tag specification for each resource type given, each tagging its team. */
|
||||
private static Response runInstances(User user, String... typesAndTeams) {
|
||||
return tagSpecifications(user.query("ec2", "RunInstances").formParam("ImageId", IMAGE)
|
||||
.formParam("InstanceType", "t3.micro").formParam("MinCount", "1").formParam("MaxCount", "1"),
|
||||
typesAndTeams).post("/");
|
||||
}
|
||||
|
||||
private static Response createVpc(User user, String... typesAndTeams) {
|
||||
return tagSpecifications(user.query("ec2", "CreateVpc").formParam("CidrBlock", "10.20.0.0/16"), typesAndTeams)
|
||||
.post("/");
|
||||
}
|
||||
|
||||
private static RequestSpecification tagSpecifications(RequestSpecification request, String... typesAndTeams) {
|
||||
for (int i = 0; i < typesAndTeams.length; i += 2) {
|
||||
String specification = "TagSpecification." + (i / 2 + 1);
|
||||
request = request.formParam(specification + ".ResourceType", typesAndTeams[i])
|
||||
.formParam(specification + ".Tag.1.Key", "team")
|
||||
.formParam(specification + ".Tag.1.Value", typesAndTeams[i + 1]);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
private void terminateLater(Response launched) {
|
||||
String instanceId = launched.then().statusCode(200).extract().xmlPath()
|
||||
.getString("RunInstancesResponse.instancesSet.item.instanceId");
|
||||
cleanup.register(() -> admin("ec2").formParam("Action", "TerminateInstances")
|
||||
.formParam("InstanceId.1", instanceId).post("/"));
|
||||
}
|
||||
|
||||
private void deleteQueueLater(Response created) {
|
||||
String url = created.then().statusCode(200).extract().xmlPath()
|
||||
.getString("CreateQueueResponse.CreateQueueResult.QueueUrl");
|
||||
cleanup.register(() -> admin("sqs").formParam("Action", "DeleteQueue").formParam("QueueUrl", url).post("/"));
|
||||
}
|
||||
|
||||
private static String createTagsFor(String createAction) {
|
||||
return "{\"Effect\":\"Allow\",\"Action\":\"ec2:CreateTags\",\"Resource\":\"*\","
|
||||
+ "\"Condition\":{\"StringEquals\":{\"ec2:CreateAction\":\"" + createAction + "\"}}}";
|
||||
}
|
||||
|
||||
/** 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));
|
||||
}
|
||||
|
||||
private static void refusedRest(ValidatableResponse response, String action) {
|
||||
response.statusCode(403).body(containsString("not authorized to perform: " + action))
|
||||
.body(not(containsString("iam:PassRole")));
|
||||
}
|
||||
|
||||
private static String allow(String action) {
|
||||
return "{\"Effect\":\"Allow\",\"Action\":\"" + action + "\",\"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 rest(String service) {
|
||||
return given().header("Authorization", auth(accessKeyId, service)).contentType("application/json");
|
||||
}
|
||||
|
||||
RequestSpecification cbor(String service) {
|
||||
return given().header("Authorization", auth(accessKeyId, service)).header("smithy-protocol", "rpc-v2-cbor")
|
||||
.contentType("application/cbor").accept("application/cbor");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1237,6 +1237,24 @@ class ResourceArnBuilderTest {
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function", arn);
|
||||
}
|
||||
|
||||
/** CreateFunction is checked on the function its body names, in the caller's account and Region. */
|
||||
@Test
|
||||
void lambdaCreateFunctionIsCheckedOnTheFunctionItsBodyNames() {
|
||||
when(uriInfo.getPath()).thenReturn("/2015-03-31/functions");
|
||||
when(ctx.getMethod()).thenReturn("POST");
|
||||
setJsonBody("{\"FunctionName\":\"my-function\",\"Runtime\":\"nodejs20.x\"}");
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function",
|
||||
builder.build("lambda", ctx, "us-east-1", "000000000000"));
|
||||
setJsonBody("{\"FunctionName\":\"arn:aws:lambda:us-east-1:111122223333:function:my-function\"}");
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function",
|
||||
builder.build("lambda", ctx, "us-east-1", "000000000000"));
|
||||
setJsonBody("{\"Runtime\":\"nodejs20.x\"}");
|
||||
assertEquals("*", builder.build("lambda", ctx, "us-east-1", "000000000000"));
|
||||
when(ctx.getMethod()).thenReturn("GET");
|
||||
setJsonBody("{\"FunctionName\":\"my-function\"}");
|
||||
assertEquals("*", builder.build("lambda", ctx, "us-east-1", "000000000000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lambdaFunctionArnKeepsTheAccountItNames() {
|
||||
when(uriInfo.getPath()).thenReturn(
|
||||
|
||||
Reference in new issue
Block a user