mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(iam): enforce tag constraints across every IAM tagging action (#4485)
extractTags collapsed Tags.member.N into a map before any count was taken, so a 51-member list with one repeated key slipped through as 50 tags, and TagUser, TagRole, TagPolicy and TagOpenIDConnectProvider bounded nothing. The request-shape rules now live in the handler, on the members as sent: tagListType and tagKeyListType are capped at 50 for every tag and untag action, keys must be 1-128 characters and values at most 256, both matching IAM's tag character pattern, with errors naming the offending member index. Users, roles, policies and OIDC providers now also enforce the 50-tag per-resource quota (LimitExceeded, as instance and SAML providers already did), and the tag read-modify-write runs under a lock so two requests that each fit cannot together push a resource past it. Closes #4407
This commit is contained in:
1 parent
1451693cda
commit
64375691ac
5 files changed
+577
-65
No files matched your search
@@ -27,6 +27,7 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
@@ -38,6 +39,11 @@ import java.util.stream.Stream;
|
||||
public class IamQueryHandler {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(IamQueryHandler.class);
|
||||
private static final int MAX_TAG_LIST_MEMBERS = 50;
|
||||
private static final int MAX_TAG_KEY_LENGTH = 128;
|
||||
private static final int MAX_TAG_VALUE_LENGTH = 256;
|
||||
private static final Pattern TAG_KEY_PATTERN = Pattern.compile("[\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]+");
|
||||
private static final Pattern TAG_VALUE_PATTERN = Pattern.compile("[\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*");
|
||||
|
||||
private final IamService iamService;
|
||||
private final IamPolicyEvaluator policyEvaluator;
|
||||
@@ -380,7 +386,6 @@ public class IamQueryHandler {
|
||||
}
|
||||
|
||||
private Response handleCreateSAMLProvider(MultivaluedMap<String, String> params, String authorization) {
|
||||
checkSamlTagMembers(params);
|
||||
SAMLProvider provider = samlProviderService.create(regionResolver.getPartition(),
|
||||
accountResolver.resolve(authorization), getParam(params, "Name"),
|
||||
getParam(params, "SAMLMetadataDocument"), extractTags(params));
|
||||
@@ -417,7 +422,6 @@ public class IamQueryHandler {
|
||||
|
||||
private Response handleTagSAMLProvider(MultivaluedMap<String, String> params, String authorization) {
|
||||
String accountId = accountResolver.resolve(authorization);
|
||||
checkSamlTagMembers(params);
|
||||
samlProviderService.tag(accountId, getParam(params, "SAMLProviderArn"), extractTags(params));
|
||||
return Response.ok(AwsQueryResponse.envelopeNoResult("TagSAMLProvider", AwsNamespaces.IAM)).build();
|
||||
}
|
||||
@@ -1710,33 +1714,61 @@ public class IamQueryHandler {
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Enforces {@code tagListType}'s {@code max: 50} on the members as sent. extractTags collapses
|
||||
* repeated keys into a map, and AWS resolves a repeated key by overwriting rather than
|
||||
* rejecting, so counting the map would let a 51-member list through whenever any key repeats.
|
||||
* Every IAM request that carries tags types them as {@code tagListType}, whose {@code max: 50}
|
||||
* binds the members as sent, so the count is taken here, before the map collapses repeated keys.
|
||||
*/
|
||||
private void checkSamlTagMembers(MultivaluedMap<String, String> params) {
|
||||
int members = 0;
|
||||
while (params.getFirst("Tags.member." + (members + 1) + ".Key") != null) {
|
||||
members++;
|
||||
}
|
||||
if (members > SAMLProviderService.MAX_TAGS_PER_SAML_PROVIDER) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Value at 'tags' failed to satisfy constraint: Member must have length "
|
||||
+ "less than or equal to " + SAMLProviderService.MAX_TAGS_PER_SAML_PROVIDER, 400);
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, String> extractTags(MultivaluedMap<String, String> params) {
|
||||
Map<String, String> tags = new HashMap<>();
|
||||
List<Map.Entry<String, String>> members = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String key = params.getFirst("Tags.member." + i + ".Key");
|
||||
String value = params.getFirst("Tags.member." + i + ".Value");
|
||||
if (key == null) break;
|
||||
tags.put(key, value != null ? value : "");
|
||||
members.add(Map.entry(key, value != null ? value : ""));
|
||||
}
|
||||
checkListLength(members.size(), "tags");
|
||||
Map<String, String> tags = new HashMap<>();
|
||||
for (int i = 0; i < members.size(); i++) {
|
||||
String key = members.get(i).getKey();
|
||||
String value = members.get(i).getValue();
|
||||
String at = "tags." + (i + 1) + ".member";
|
||||
if (key.isEmpty()) {
|
||||
throw tagValidationError(key, at + ".key", "Member must have length greater than or equal to 1");
|
||||
}
|
||||
if (key.codePointCount(0, key.length()) > MAX_TAG_KEY_LENGTH) {
|
||||
throw tagValidationError(key, at + ".key",
|
||||
"Member must have length less than or equal to " + MAX_TAG_KEY_LENGTH);
|
||||
}
|
||||
if (!TAG_KEY_PATTERN.matcher(key).matches()) {
|
||||
throw tagValidationError(key, at + ".key",
|
||||
"Member must satisfy regular expression pattern: " + TAG_KEY_PATTERN.pattern());
|
||||
}
|
||||
if (value.codePointCount(0, value.length()) > MAX_TAG_VALUE_LENGTH) {
|
||||
throw tagValidationError(value, at + ".value",
|
||||
"Member must have length less than or equal to " + MAX_TAG_VALUE_LENGTH);
|
||||
}
|
||||
if (!TAG_VALUE_PATTERN.matcher(value).matches()) {
|
||||
throw tagValidationError(value, at + ".value",
|
||||
"Member must satisfy regular expression pattern: " + TAG_VALUE_PATTERN.pattern());
|
||||
}
|
||||
tags.put(key, value);
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
private static void checkListLength(int members, String param) {
|
||||
if (members > MAX_TAG_LIST_MEMBERS) {
|
||||
throw new AwsException("ValidationError",
|
||||
"1 validation error detected: Value at '" + param + "' failed to satisfy constraint: "
|
||||
+ "Member must have length less than or equal to " + MAX_TAG_LIST_MEMBERS, 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException tagValidationError(String value, String at, String constraint) {
|
||||
return new AwsException("ValidationError",
|
||||
"1 validation error detected: Value '" + value + "' at '" + at + "' failed to satisfy constraint: "
|
||||
+ constraint, 400);
|
||||
}
|
||||
|
||||
private List<String> getMemberList(MultivaluedMap<String, String> params, String name) {
|
||||
List<String> values = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
@@ -1754,6 +1786,7 @@ public class IamQueryHandler {
|
||||
if (key == null) break;
|
||||
keys.add(key);
|
||||
}
|
||||
checkListLength(keys.size(), "tagKeys");
|
||||
return keys;
|
||||
}
|
||||
|
||||
|
||||
@@ -98,6 +98,12 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
/** Guards the read-modify-write in the OIDC provider mutators. */
|
||||
private final Object oidcProviderLock = new Object();
|
||||
|
||||
/**
|
||||
* Guards the tag read-modify-write on users, roles, policies and instance profiles, so two
|
||||
* requests that each fit the per-resource quota cannot together push a resource past it.
|
||||
*/
|
||||
private final Object tagLock = new Object();
|
||||
|
||||
/** CSPRNG for long-term secret access keys; ordinary resource IDs keep using {@link ThreadLocalRandom}. */
|
||||
private final SecureRandom secureRandom = new SecureRandom();
|
||||
|
||||
@@ -119,8 +125,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
/** pathType: a bare slash, or a slash-delimited run of {@code !}-{@code ~}. */
|
||||
private static final Pattern IAM_PATH_PATTERN = Pattern.compile("(/)|(/[\\x21-\\x7E]+/)");
|
||||
private static final int IAM_PATH_MAX_LENGTH = 512;
|
||||
/** {@code tagListType} / {@code tagKeyListType} are both {@code max: 50}. */
|
||||
private static final int MAX_TAGS_PER_INSTANCE_PROFILE = 50;
|
||||
private static final int MAX_TAGS_PER_RESOURCE = 50;
|
||||
private static final String ROOT_FEATURES_KEY = "org-root-features";
|
||||
private static final String CREDENTIAL_REPORT_KEY = "credential-report";
|
||||
/** AWS generates a fresh report only if the most recent one is older than this. */
|
||||
@@ -514,15 +519,19 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
|
||||
public void tagUser(String userName, Map<String, String> newTags) {
|
||||
IamUser user = getUser(userName);
|
||||
user.getTags().putAll(newTags);
|
||||
users.put(userName, user);
|
||||
synchronized (tagLock) {
|
||||
IamUser user = getUser(userName);
|
||||
user.setTags(mergeTagsWithinQuota(user.getTags(), newTags, "TagsPerUser"));
|
||||
users.put(userName, user);
|
||||
}
|
||||
}
|
||||
|
||||
public void untagUser(String userName, List<String> tagKeys) {
|
||||
IamUser user = getUser(userName);
|
||||
tagKeys.forEach(user.getTags()::remove);
|
||||
users.put(userName, user);
|
||||
synchronized (tagLock) {
|
||||
IamUser user = getUser(userName);
|
||||
tagKeys.forEach(user.getTags()::remove);
|
||||
users.put(userName, user);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, String> listUserTags(String userName) {
|
||||
@@ -874,15 +883,19 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
|
||||
public void tagRole(String roleName, Map<String, String> newTags) {
|
||||
IamRole role = getRole(roleName);
|
||||
role.getTags().putAll(newTags);
|
||||
roles.put(roleName, role);
|
||||
synchronized (tagLock) {
|
||||
IamRole role = getRole(roleName);
|
||||
role.setTags(mergeTagsWithinQuota(role.getTags(), newTags, "TagsPerRole"));
|
||||
roles.put(roleName, role);
|
||||
}
|
||||
}
|
||||
|
||||
public void untagRole(String roleName, List<String> tagKeys) {
|
||||
IamRole role = getRole(roleName);
|
||||
tagKeys.forEach(role.getTags()::remove);
|
||||
roles.put(roleName, role);
|
||||
synchronized (tagLock) {
|
||||
IamRole role = getRole(roleName);
|
||||
tagKeys.forEach(role.getTags()::remove);
|
||||
roles.put(roleName, role);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, String> listRoleTags(String roleName) {
|
||||
@@ -1241,16 +1254,20 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
|
||||
public void tagPolicy(String policyArn, Map<String, String> newTags) {
|
||||
rejectIfAwsManaged(policyArn);
|
||||
IamPolicy policy = getPolicy(policyArn);
|
||||
policy.getTags().putAll(newTags);
|
||||
policies.put(policyArn, policy);
|
||||
synchronized (tagLock) {
|
||||
IamPolicy policy = getPolicy(policyArn);
|
||||
policy.setTags(mergeTagsWithinQuota(policy.getTags(), newTags, "TagsPerPolicy"));
|
||||
policies.put(policyArn, policy);
|
||||
}
|
||||
}
|
||||
|
||||
public void untagPolicy(String policyArn, List<String> tagKeys) {
|
||||
rejectIfAwsManaged(policyArn);
|
||||
IamPolicy policy = getPolicy(policyArn);
|
||||
tagKeys.forEach(policy.getTags()::remove);
|
||||
policies.put(policyArn, policy);
|
||||
synchronized (tagLock) {
|
||||
IamPolicy policy = getPolicy(policyArn);
|
||||
tagKeys.forEach(policy.getTags()::remove);
|
||||
policies.put(policyArn, policy);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, String> listPolicyTags(String policyArn) {
|
||||
@@ -2062,9 +2079,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
synchronized (oidcProviderLock) {
|
||||
OpenIDConnectProvider provider = getOpenIDConnectProvider(arn);
|
||||
Map<String, String> merged = new LinkedHashMap<>(provider.getTags());
|
||||
merged.putAll(newTags);
|
||||
provider.setTags(merged);
|
||||
provider.setTags(mergeTagsWithinQuota(provider.getTags(), newTags, "TagsPerOpenIdConnectProvider"));
|
||||
oidcProviders.put(arn, provider);
|
||||
}
|
||||
}
|
||||
@@ -2806,34 +2821,33 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
|
||||
public void tagInstanceProfile(String instanceProfileName, Map<String, String> newTags) {
|
||||
// Request shape before resource lookup, matching untagInstanceProfile and AWS's order.
|
||||
// Name shape before resource lookup, matching untagInstanceProfile.
|
||||
validateIamResourceName(instanceProfileName, "InstanceProfileName");
|
||||
if (newTags != null && newTags.size() > MAX_TAGS_PER_INSTANCE_PROFILE) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Value at 'tags' failed to satisfy constraint: Member must have length "
|
||||
+ "less than or equal to " + MAX_TAGS_PER_INSTANCE_PROFILE, 400);
|
||||
synchronized (tagLock) {
|
||||
InstanceProfile profile = getInstanceProfile(instanceProfileName);
|
||||
profile.setTags(mergeTagsWithinQuota(profile.getTags(), newTags, "TagsPerInstanceProfile"));
|
||||
instanceProfiles.put(instanceProfileName, profile);
|
||||
}
|
||||
InstanceProfile profile = getInstanceProfile(instanceProfileName);
|
||||
Map<String, String> merged = new LinkedHashMap<>(profile.getTags());
|
||||
}
|
||||
|
||||
private static Map<String, String> mergeTagsWithinQuota(Map<String, String> current,
|
||||
Map<String, String> newTags, String quota) {
|
||||
Map<String, String> merged = new LinkedHashMap<>(current);
|
||||
merged.putAll(newTags == null ? Map.of() : newTags);
|
||||
if (merged.size() > MAX_TAGS_PER_INSTANCE_PROFILE) {
|
||||
if (merged.size() > MAX_TAGS_PER_RESOURCE) {
|
||||
throw new AwsException("LimitExceeded",
|
||||
"Cannot exceed quota for TagsPerInstanceProfile: " + MAX_TAGS_PER_INSTANCE_PROFILE, 409);
|
||||
"Cannot exceed quota for " + quota + ": " + MAX_TAGS_PER_RESOURCE, 409);
|
||||
}
|
||||
profile.getTags().putAll(newTags == null ? Map.of() : newTags);
|
||||
instanceProfiles.put(instanceProfileName, profile);
|
||||
return merged;
|
||||
}
|
||||
|
||||
public void untagInstanceProfile(String instanceProfileName, List<String> tagKeys) {
|
||||
validateIamResourceName(instanceProfileName, "InstanceProfileName");
|
||||
if (tagKeys != null && tagKeys.size() > MAX_TAGS_PER_INSTANCE_PROFILE) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Value at 'tagKeys' failed to satisfy constraint: Member must have length "
|
||||
+ "less than or equal to " + MAX_TAGS_PER_INSTANCE_PROFILE, 400);
|
||||
synchronized (tagLock) {
|
||||
InstanceProfile profile = getInstanceProfile(instanceProfileName);
|
||||
tagKeys.forEach(profile.getTags()::remove);
|
||||
instanceProfiles.put(instanceProfileName, profile);
|
||||
}
|
||||
InstanceProfile profile = getInstanceProfile(instanceProfileName);
|
||||
tagKeys.forEach(profile.getTags()::remove);
|
||||
instanceProfiles.put(instanceProfileName, profile);
|
||||
}
|
||||
|
||||
public Map<String, String> listInstanceProfileTags(String instanceProfileName) {
|
||||
|
||||
@@ -183,11 +183,6 @@ public class SAMLProviderService {
|
||||
}
|
||||
|
||||
public void untag(String accountId, String arn, List<String> tagKeys) {
|
||||
if (tagKeys != null && tagKeys.size() > MAX_TAGS_PER_SAML_PROVIDER) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Value at 'tagKeys' failed to satisfy constraint: Member must have length "
|
||||
+ "less than or equal to " + MAX_TAGS_PER_SAML_PROVIDER, 400);
|
||||
}
|
||||
synchronized (providerLock) {
|
||||
SAMLProvider provider = getForAccount(accountId, arn);
|
||||
Map<String, String> remaining = new LinkedHashMap<>(provider.getTags());
|
||||
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import org.junit.jupiter.api.DynamicTest;
|
||||
import org.junit.jupiter.api.TestFactory;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.ToIntFunction;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Two tag requests that each fit the 50-tag quota must not together push one resource past it.
|
||||
* Each pair is released from a shared latch so both merge-and-check steps overlap.
|
||||
*/
|
||||
class IamTagQuotaConcurrencyTest {
|
||||
|
||||
private static final int TRIALS = 200;
|
||||
private static final String POLICY_DOCUMENT =
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}";
|
||||
private static final String POLICY_ARN = "arn:aws:iam::000000000000:policy/p";
|
||||
|
||||
private static IamService newIamService() {
|
||||
return new IamService(
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new RegionResolver("eu-central-1", "000000000000"), false);
|
||||
}
|
||||
|
||||
private static Map<String, String> thirtyTags(String prefix) {
|
||||
Map<String, String> tags = new HashMap<>();
|
||||
for (int i = 1; i <= 30; i++) {
|
||||
tags.put(prefix + i, "v");
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
private record Scenario(String name, Consumer<IamService> create,
|
||||
BiConsumer<IamService, Map<String, String>> tagger, ToIntFunction<IamService> count) {}
|
||||
|
||||
@TestFactory
|
||||
Stream<DynamicTest> racingTagRequestsNeverExceedTheQuota() {
|
||||
List<Scenario> scenarios = List.of(
|
||||
new Scenario("user", iam -> iam.createUser("u", "/"),
|
||||
(iam, tags) -> iam.tagUser("u", tags), iam -> iam.getUser("u").getTags().size()),
|
||||
new Scenario("role", iam -> iam.createRole("r", "/", "{}", null, 3600, null),
|
||||
(iam, tags) -> iam.tagRole("r", tags), iam -> iam.getRole("r").getTags().size()),
|
||||
new Scenario("policy", iam -> iam.createPolicy("p", "/", null, POLICY_DOCUMENT, null),
|
||||
(iam, tags) -> iam.tagPolicy(POLICY_ARN, tags), iam -> iam.getPolicy(POLICY_ARN).getTags().size()),
|
||||
new Scenario("instanceProfile", iam -> iam.createInstanceProfile("p", "/"),
|
||||
(iam, tags) -> iam.tagInstanceProfile("p", tags),
|
||||
iam -> iam.getInstanceProfile("p").getTags().size()));
|
||||
|
||||
return scenarios.stream().map(s -> DynamicTest.dynamicTest(s.name(), () -> {
|
||||
ExecutorService pool = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
for (int trial = 0; trial < TRIALS; trial++) {
|
||||
IamService iam = newIamService();
|
||||
s.create().accept(iam);
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
Future<Boolean> first = pool.submit(() -> tagAfter(start, () -> s.tagger().accept(iam, thirtyTags("a"))));
|
||||
Future<Boolean> second = pool.submit(() -> tagAfter(start, () -> s.tagger().accept(iam, thirtyTags("b"))));
|
||||
start.countDown();
|
||||
int succeeded = (first.get(10, TimeUnit.SECONDS) ? 1 : 0) + (second.get(10, TimeUnit.SECONDS) ? 1 : 0);
|
||||
|
||||
assertEquals(1, succeeded, s.name() + " trial " + trial + ": exactly one request fits");
|
||||
int stored = s.count().applyAsInt(iam);
|
||||
assertTrue(stored <= 50, s.name() + " trial " + trial + ": stored " + stored + " tags");
|
||||
}
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
private static boolean tagAfter(CountDownLatch start, Runnable tag) throws InterruptedException {
|
||||
start.await();
|
||||
try {
|
||||
tag.run();
|
||||
return true;
|
||||
} catch (AwsException e) {
|
||||
assertEquals("LimitExceeded", e.getErrorCode());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+370
@@ -0,0 +1,370 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
/**
|
||||
* Tag validation shared by every IAM tagging action. {@code tagListType} and {@code tagKeyListType}
|
||||
* are {@code max: 50} on the members as sent, so a 51-member list is rejected even when a repeated
|
||||
* key would collapse it to 50. Keys and values carry their own length and character constraints,
|
||||
* and each resource holds at most 50 tags however many requests they arrive in.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class IamTagValidationIntegrationTest {
|
||||
|
||||
private static final String IAM_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String TRUST_POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}";
|
||||
private static final String POLICY_DOCUMENT = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}";
|
||||
private static final String THUMBPRINT = "9e99a48a9960b14926bb7f3b02e22da2b0ab7280";
|
||||
|
||||
private static RequestSpecification iam(String action) {
|
||||
return given().header("Authorization", IAM_AUTH).formParam("Action", action);
|
||||
}
|
||||
|
||||
private static RequestSpecification withTags(RequestSpecification request, int distinctKeys, boolean repeatFirstKey) {
|
||||
for (int i = 1; i <= distinctKeys; i++) {
|
||||
request.formParam("Tags.member." + i + ".Key", "key" + i)
|
||||
.formParam("Tags.member." + i + ".Value", "value" + i);
|
||||
}
|
||||
if (repeatFirstKey) {
|
||||
int last = distinctKeys + 1;
|
||||
request.formParam("Tags.member." + last + ".Key", "key1")
|
||||
.formParam("Tags.member." + last + ".Value", "again");
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
private static void assertRejected(RequestSpecification request) {
|
||||
request.when().post("/").then()
|
||||
.statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
|
||||
.body(containsString("Member must have length less than or equal to 50"));
|
||||
}
|
||||
|
||||
private static void assertNoSuchEntity(RequestSpecification request) {
|
||||
request.when().post("/").then()
|
||||
.statusCode(404)
|
||||
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
|
||||
}
|
||||
|
||||
private static String unique(String prefix) {
|
||||
return prefix + "-" + System.nanoTime();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUserWithRepeatedKeyPastFiftyMembersIsRejected() {
|
||||
String name = unique("tag-max-user");
|
||||
assertRejected(withTags(iam("CreateUser").formParam("UserName", name), 50, true));
|
||||
assertNoSuchEntity(iam("GetUser").formParam("UserName", name));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagUserWithRepeatedKeyPastFiftyMembersIsRejected() {
|
||||
String name = unique("tag-max-user");
|
||||
iam("CreateUser").formParam("UserName", name).when().post("/").then().statusCode(200);
|
||||
assertRejected(withTags(iam("TagUser").formParam("UserName", name), 50, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagUserBeyondFiftyDistinctKeysIsRejected() {
|
||||
String name = unique("tag-max-user");
|
||||
iam("CreateUser").formParam("UserName", name).when().post("/").then().statusCode(200);
|
||||
assertRejected(withTags(iam("TagUser").formParam("UserName", name), 60, false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagUserWithExactlyFiftyMembersIsAccepted() {
|
||||
String name = unique("tag-max-user");
|
||||
iam("CreateUser").formParam("UserName", name).when().post("/").then().statusCode(200);
|
||||
withTags(iam("TagUser").formParam("UserName", name), 50, false)
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRoleWithRepeatedKeyPastFiftyMembersIsRejected() {
|
||||
String name = unique("tag-max-role");
|
||||
assertRejected(withTags(iam("CreateRole").formParam("RoleName", name)
|
||||
.formParam("AssumeRolePolicyDocument", TRUST_POLICY), 50, true));
|
||||
assertNoSuchEntity(iam("GetRole").formParam("RoleName", name));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagRoleWithRepeatedKeyPastFiftyMembersIsRejected() {
|
||||
String name = unique("tag-max-role");
|
||||
iam("CreateRole").formParam("RoleName", name).formParam("AssumeRolePolicyDocument", TRUST_POLICY)
|
||||
.when().post("/").then().statusCode(200);
|
||||
assertRejected(withTags(iam("TagRole").formParam("RoleName", name), 50, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPolicyWithRepeatedKeyPastFiftyMembersIsRejected() {
|
||||
String name = unique("tag-max-policy");
|
||||
assertRejected(withTags(iam("CreatePolicy").formParam("PolicyName", name)
|
||||
.formParam("PolicyDocument", POLICY_DOCUMENT), 50, true));
|
||||
assertNoSuchEntity(iam("GetPolicy").formParam("PolicyArn", "arn:aws:iam::" + ACCOUNT + ":policy/" + name));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagPolicyWithRepeatedKeyPastFiftyMembersIsRejected() {
|
||||
String name = unique("tag-max-policy");
|
||||
String arn = iam("CreatePolicy").formParam("PolicyName", name).formParam("PolicyDocument", POLICY_DOCUMENT)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().xmlPath().getString("CreatePolicyResponse.CreatePolicyResult.Policy.Arn");
|
||||
assertRejected(withTags(iam("TagPolicy").formParam("PolicyArn", arn), 50, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createInstanceProfileWithRepeatedKeyPastFiftyMembersIsRejected() {
|
||||
String name = unique("tag-max-profile");
|
||||
assertRejected(withTags(iam("CreateInstanceProfile").formParam("InstanceProfileName", name), 50, true));
|
||||
assertNoSuchEntity(iam("GetInstanceProfile").formParam("InstanceProfileName", name));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagInstanceProfileWithRepeatedKeyPastFiftyMembersIsRejected() {
|
||||
String name = unique("tag-max-profile");
|
||||
iam("CreateInstanceProfile").formParam("InstanceProfileName", name)
|
||||
.when().post("/").then().statusCode(200);
|
||||
assertRejected(withTags(iam("TagInstanceProfile").formParam("InstanceProfileName", name), 50, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createOpenIDConnectProviderWithRepeatedKeyPastFiftyMembersIsRejected() {
|
||||
String path = unique("tag-max-create");
|
||||
assertRejected(withTags(iam("CreateOpenIDConnectProvider")
|
||||
.formParam("Url", "https://oidc.tag-max.example.com/" + path)
|
||||
.formParam("ThumbprintList.member.1", THUMBPRINT), 50, true));
|
||||
assertNoSuchEntity(iam("GetOpenIDConnectProvider").formParam("OpenIDConnectProviderArn",
|
||||
"arn:aws:iam::" + ACCOUNT + ":oidc-provider/oidc.tag-max.example.com/" + path));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagOpenIDConnectProviderWithRepeatedKeyPastFiftyMembersIsRejected() {
|
||||
String arn = iam("CreateOpenIDConnectProvider")
|
||||
.formParam("Url", "https://oidc.tag-max.example.com/" + unique("tag-max-tag"))
|
||||
.formParam("ThumbprintList.member.1", THUMBPRINT)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().xmlPath().getString(
|
||||
"CreateOpenIDConnectProviderResponse.CreateOpenIDConnectProviderResult.OpenIDConnectProviderArn");
|
||||
assertRejected(withTags(iam("TagOpenIDConnectProvider").formParam("OpenIDConnectProviderArn", arn), 50, true));
|
||||
}
|
||||
|
||||
private static void createUser(String name) {
|
||||
iam("CreateUser").formParam("UserName", name).when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static RequestSpecification tagUser(String name, int from, int to) {
|
||||
RequestSpecification request = iam("TagUser").formParam("UserName", name);
|
||||
for (int i = from; i <= to; i++) {
|
||||
int member = i - from + 1;
|
||||
request.formParam("Tags.member." + member + ".Key", "key" + i)
|
||||
.formParam("Tags.member." + member + ".Value", "value" + i);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
private static RequestSpecification withTagKeys(RequestSpecification request, int count) {
|
||||
for (int i = 1; i <= count; i++) {
|
||||
request.formParam("TagKeys.member." + i, "key" + i);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
private static void assertQuotaExceeded(RequestSpecification request, String quota) {
|
||||
request.when().post("/").then()
|
||||
.statusCode(409)
|
||||
.body("ErrorResponse.Error.Code", equalTo("LimitExceeded"))
|
||||
.body("ErrorResponse.Error.Message", equalTo("Cannot exceed quota for " + quota + ": 50"));
|
||||
}
|
||||
|
||||
private static RequestSpecification singleTag(RequestSpecification request, String key, String value) {
|
||||
return request.formParam("Tags.member.1.Key", key).formParam("Tags.member.1.Value", value);
|
||||
}
|
||||
|
||||
private static void assertInvalidTag(RequestSpecification request, String at, String constraint) {
|
||||
request.when().post("/").then()
|
||||
.statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
|
||||
.body("ErrorResponse.Error.Message",
|
||||
containsString("at '" + at + "' failed to satisfy constraint: " + constraint));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagUserPastFiftyAcrossRequestsIsRejectedWhole() {
|
||||
String name = unique("tag-quota-user");
|
||||
createUser(name);
|
||||
tagUser(name, 1, 30).when().post("/").then().statusCode(200);
|
||||
assertQuotaExceeded(tagUser(name, 31, 60), "TagsPerUser");
|
||||
|
||||
iam("ListUserTags").formParam("UserName", name).when().post("/").then()
|
||||
.statusCode(200)
|
||||
.body("ListUserTagsResponse.ListUserTagsResult.Tags.member.size()", equalTo(30));
|
||||
}
|
||||
|
||||
@Test
|
||||
void retaggingExistingKeysAtFiftyStaysWithinQuota() {
|
||||
String name = unique("tag-quota-user");
|
||||
createUser(name);
|
||||
tagUser(name, 1, 50).when().post("/").then().statusCode(200);
|
||||
tagUser(name, 1, 50).when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagRolePastFiftyAcrossRequestsIsRejected() {
|
||||
String name = unique("tag-quota-role");
|
||||
iam("CreateRole").formParam("RoleName", name).formParam("AssumeRolePolicyDocument", TRUST_POLICY)
|
||||
.when().post("/").then().statusCode(200);
|
||||
withTags(iam("TagRole").formParam("RoleName", name), 30, false).when().post("/").then().statusCode(200);
|
||||
RequestSpecification second = iam("TagRole").formParam("RoleName", name);
|
||||
for (int i = 1; i <= 30; i++) {
|
||||
second.formParam("Tags.member." + i + ".Key", "other" + i).formParam("Tags.member." + i + ".Value", "v");
|
||||
}
|
||||
assertQuotaExceeded(second, "TagsPerRole");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagPolicyPastFiftyAcrossRequestsIsRejected() {
|
||||
String arn = iam("CreatePolicy").formParam("PolicyName", unique("tag-quota-policy"))
|
||||
.formParam("PolicyDocument", POLICY_DOCUMENT)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().xmlPath().getString("CreatePolicyResponse.CreatePolicyResult.Policy.Arn");
|
||||
withTags(iam("TagPolicy").formParam("PolicyArn", arn), 30, false).when().post("/").then().statusCode(200);
|
||||
RequestSpecification second = iam("TagPolicy").formParam("PolicyArn", arn);
|
||||
for (int i = 1; i <= 30; i++) {
|
||||
second.formParam("Tags.member." + i + ".Key", "other" + i).formParam("Tags.member." + i + ".Value", "v");
|
||||
}
|
||||
assertQuotaExceeded(second, "TagsPerPolicy");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagOpenIDConnectProviderPastFiftyAcrossRequestsIsRejected() {
|
||||
String arn = iam("CreateOpenIDConnectProvider")
|
||||
.formParam("Url", "https://oidc.tag-max.example.com/" + unique("tag-quota"))
|
||||
.formParam("ThumbprintList.member.1", THUMBPRINT)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().xmlPath().getString(
|
||||
"CreateOpenIDConnectProviderResponse.CreateOpenIDConnectProviderResult.OpenIDConnectProviderArn");
|
||||
withTags(iam("TagOpenIDConnectProvider").formParam("OpenIDConnectProviderArn", arn), 30, false)
|
||||
.when().post("/").then().statusCode(200);
|
||||
RequestSpecification second = iam("TagOpenIDConnectProvider").formParam("OpenIDConnectProviderArn", arn);
|
||||
for (int i = 1; i <= 30; i++) {
|
||||
second.formParam("Tags.member." + i + ".Key", "other" + i).formParam("Tags.member." + i + ".Value", "v");
|
||||
}
|
||||
assertQuotaExceeded(second, "TagsPerOpenIdConnectProvider");
|
||||
}
|
||||
|
||||
@Test
|
||||
void untagBeyondFiftyKeysIsRejectedOnEveryUntagAction() {
|
||||
String user = unique("untag-max-user");
|
||||
createUser(user);
|
||||
assertRejected(withTagKeys(iam("UntagUser").formParam("UserName", user), 51));
|
||||
|
||||
String role = unique("untag-max-role");
|
||||
iam("CreateRole").formParam("RoleName", role).formParam("AssumeRolePolicyDocument", TRUST_POLICY)
|
||||
.when().post("/").then().statusCode(200);
|
||||
assertRejected(withTagKeys(iam("UntagRole").formParam("RoleName", role), 51));
|
||||
|
||||
String policyArn = iam("CreatePolicy").formParam("PolicyName", unique("untag-max-policy"))
|
||||
.formParam("PolicyDocument", POLICY_DOCUMENT)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().xmlPath().getString("CreatePolicyResponse.CreatePolicyResult.Policy.Arn");
|
||||
assertRejected(withTagKeys(iam("UntagPolicy").formParam("PolicyArn", policyArn), 51));
|
||||
|
||||
String oidcArn = iam("CreateOpenIDConnectProvider")
|
||||
.formParam("Url", "https://oidc.tag-max.example.com/" + unique("untag-max"))
|
||||
.formParam("ThumbprintList.member.1", THUMBPRINT)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().xmlPath().getString(
|
||||
"CreateOpenIDConnectProviderResponse.CreateOpenIDConnectProviderResult.OpenIDConnectProviderArn");
|
||||
assertRejected(withTagKeys(iam("UntagOpenIDConnectProvider").formParam("OpenIDConnectProviderArn", oidcArn), 51));
|
||||
|
||||
withTagKeys(iam("UntagUser").formParam("UserName", user), 50).when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagKeyLongerThan128IsRejected() {
|
||||
String name = unique("tag-key-long");
|
||||
createUser(name);
|
||||
assertInvalidTag(singleTag(iam("TagUser").formParam("UserName", name), "k".repeat(129), "v"),
|
||||
"tags.1.member.key", "Member must have length less than or equal to 128");
|
||||
singleTag(iam("TagUser").formParam("UserName", name), "k".repeat(128), "v")
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* AWS measures string length in Unicode scalar values, so a letter outside the Basic
|
||||
* Multilingual Plane counts once even though Java stores it as two UTF-16 units.
|
||||
*/
|
||||
@Test
|
||||
void tagLengthLimitsCountSupplementaryCharactersOnce() {
|
||||
String name = unique("tag-supplementary");
|
||||
createUser(name);
|
||||
String scriptA = new String(Character.toChars(0x1D49C));
|
||||
singleTag(iam("TagUser").formParam("UserName", name)
|
||||
.contentType("application/x-www-form-urlencoded; charset=UTF-8"),
|
||||
scriptA.repeat(128), scriptA.repeat(256))
|
||||
.when().post("/").then().statusCode(200);
|
||||
assertInvalidTag(singleTag(iam("TagUser").formParam("UserName", name)
|
||||
.contentType("application/x-www-form-urlencoded; charset=UTF-8"), scriptA.repeat(129), "v"),
|
||||
"tags.1.member.key", "Member must have length less than or equal to 128");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyTagKeyIsRejected() {
|
||||
String name = unique("tag-key-empty");
|
||||
createUser(name);
|
||||
assertInvalidTag(singleTag(iam("TagUser").formParam("UserName", name), "", "v"),
|
||||
"tags.1.member.key", "Member must have length greater than or equal to 1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagValueLongerThan256IsRejected() {
|
||||
String name = unique("tag-value-long");
|
||||
createUser(name);
|
||||
assertInvalidTag(singleTag(iam("TagUser").formParam("UserName", name), "k", "v".repeat(257)),
|
||||
"tags.1.member.value", "Member must have length less than or equal to 256");
|
||||
singleTag(iam("TagUser").formParam("UserName", name), "k", "v".repeat(256))
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagCharactersOutsideThePatternAreRejectedAtTheirMemberIndex() {
|
||||
String name = unique("tag-chars");
|
||||
createUser(name);
|
||||
RequestSpecification badKey = iam("TagUser").formParam("UserName", name)
|
||||
.formParam("Tags.member.1.Key", "ok").formParam("Tags.member.1.Value", "ok")
|
||||
.formParam("Tags.member.2.Key", "cost#center").formParam("Tags.member.2.Value", "ok");
|
||||
assertInvalidTag(badKey, "tags.2.member.key", "Member must satisfy regular expression pattern");
|
||||
assertInvalidTag(singleTag(iam("TagUser").formParam("UserName", name), "team", "a,b"),
|
||||
"tags.1.member.value", "Member must satisfy regular expression pattern");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagWithLettersSpacesAndAllowedSymbolsIsAccepted() {
|
||||
String name = unique("tag-chars-ok");
|
||||
createUser(name);
|
||||
singleTag(iam("TagUser").formParam("UserName", name)
|
||||
.contentType("application/x-www-form-urlencoded; charset=UTF-8"),
|
||||
"Cost Center_é.:/=+-@", "Ünïcode 42 _.:/=+-@")
|
||||
.when().post("/").then().statusCode(200);
|
||||
singleTag(iam("TagUser").formParam("UserName", name), "phoneNumber", "")
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidTagOnCreateLeavesNoResourceBehind() {
|
||||
String name = unique("tag-invalid-create");
|
||||
assertInvalidTag(singleTag(iam("CreateUser").formParam("UserName", name), "bad#key", "v"),
|
||||
"tags.1.member.key", "Member must satisfy regular expression pattern");
|
||||
assertNoSuchEntity(iam("GetUser").formParam("UserName", name));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user