mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(config): add aggregation authorization CRUD (#3627)
* feat(config): add aggregation authorization CRUD PutAggregationAuthorization, DescribeAggregationAuthorizations and DeleteAggregationAuthorization were unrouted, so the JSON handler answered InvalidAction and aws_config_aggregate_authorization could not be created. Authorizations are keyed by (AuthorizedAccountId, AuthorizedAwsRegion) within the request region, persisted through StorageFactory like the other durable Config resources. Put is an upsert that preserves the ARN and creation time of an existing authorization, and accepts Tags, which land in the same tag store that ListTagsForResource reads. Delete of an absent authorization succeeds: the Config model declares no not-found error for that operation. * fix(config): remove aggregation-authorization tags on every delete attempt Tag cleanup ran only when the delete found an entry to remove. A delete that removed the authorization but did not reach the tags left them behind, and the retry that should have cleaned them up skipped the cleanup because the entry was already gone. Put reuses a deterministic ARN, so those tags reappeared on the next authorization for the same account and region. The ARN is now derived from the key instead of read off the removed entry, and its tags are dropped on every attempt. The authorization map is still persisted only when an entry was actually removed. * fix(config): apply PutAggregationAuthorization tags at creation only PutAggregationAuthorization is idempotent, and AWS applies request tags at creation only: a later Put that finds the authorization already there ignores its Tags and leaves the existing ones alone. Tagging the existing ARN on every Put let a local test retag by re-putting, which production would silently refuse. Return the existing authorization untouched and tag only the one just created. Tags still change through TagResource/UntagResource, which is the only way AWS offers. * fix(config): make aggregation authorization put/delete atomic putAggregationAuthorization did a get-then-put on the region map with nothing holding the two together, and deleteAggregationAuthorization removed-then- persisted the same way. Two concurrent Puts for one (AuthorizedAccountId, AuthorizedAwsRegion) could both find nothing and both create: the second overwrote the first's CreationTime and re-applied creation tags over a set TagResource may already have changed, so the documented idempotency held only probabilistically. Both now take the same per-key lock putConfigRule/deleteConfigRule already use for rules. The lock keys are namespaced apart from the rule keys in the shared map rather than relying on rule names never containing '|'. The regression runs many short rounds rather than one wide one, because the unlocked window is a few instructions: repeated fresh starts land the race, more threads on one start do not. It asserts reference identity, which is what distinguishes the two cases -- the store is keyed on the pair so its size is 1 either way, the ARN is derived from the key so it is equal either way, and CreationTime is epoch seconds so a racing pair created inside one second is indistinguishable by timestamp. Verified to fail with the lock removed (17 mismatches) and pass with it, five runs.
This commit is contained in:
1 parent
026abe4878
commit
97cbce205b
6 files changed
+718
-5
No files matched your search
@@ -65,6 +65,14 @@
|
||||
| `DescribeConformancePacks` | List conformance packs, paginated via `Limit`/`NextToken` |
|
||||
| `DescribeConformancePackStatus` | Get the deployment status of conformance packs |
|
||||
|
||||
### Aggregation Authorizations
|
||||
|
||||
| Action | Description |
|
||||
|---|---|
|
||||
| `PutAggregationAuthorization` | Authorize an account and region to aggregate this account's Config data |
|
||||
| `DescribeAggregationAuthorizations` | List aggregation authorizations, paginated via `Limit`/`NextToken` |
|
||||
| `DeleteAggregationAuthorization` | Revoke an aggregation authorization |
|
||||
|
||||
### Tagging
|
||||
|
||||
| Action | Description |
|
||||
@@ -144,6 +152,14 @@ aws configservice put-conformance-pack \
|
||||
# List conformance packs
|
||||
aws configservice describe-conformance-packs
|
||||
|
||||
# Authorize another account to aggregate this account's data
|
||||
aws configservice put-aggregation-authorization \
|
||||
--authorized-account-id 111122223333 \
|
||||
--authorized-aws-region eu-west-1
|
||||
|
||||
# List aggregation authorizations
|
||||
aws configservice describe-aggregation-authorizations
|
||||
|
||||
# Tag a resource
|
||||
aws configservice tag-resource \
|
||||
--resource-arn arn:aws:config:us-east-1:000000000000:config-rule/config-rule-abc123 \
|
||||
@@ -174,3 +190,7 @@ aws configservice delete-config-rule --config-rule-name s3-bucket-versioning
|
||||
configuration items or snapshots are produced.
|
||||
- Conformance pack status is always `CREATE_SUCCESSFUL`; pack templates are stored,
|
||||
not evaluated.
|
||||
- `PutAggregationAuthorization` records the authorization and returns its ARN, but no
|
||||
data is aggregated: configuration aggregators are not emulated.
|
||||
`DeleteAggregationAuthorization` on an authorization that does not exist succeeds,
|
||||
because the Config API models no "not found" error for that operation.
|
||||
+110
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackedMap;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.configservice.model.AggregationAuthorization;
|
||||
import io.github.hectorvent.floci.services.configservice.model.Compliance;
|
||||
import io.github.hectorvent.floci.services.configservice.model.ComplianceByConfigRule;
|
||||
import io.github.hectorvent.floci.services.configservice.model.ComplianceByResource;
|
||||
@@ -40,6 +41,7 @@ import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@ApplicationScoped
|
||||
@@ -70,6 +72,10 @@ public class AwsConfigService {
|
||||
private static final int MAX_COMPLIANCE_RESOURCE_TYPES = 100;
|
||||
/** {@code DescribeConfigRulesRequest.ConfigRuleNames} is {@code max: 25}. */
|
||||
private static final int MAX_DESCRIBE_CONFIG_RULE_NAMES = 25;
|
||||
/** {@code DescribeAggregationAuthorizationsRequest.Limit} is {@code max: 100}. */
|
||||
private static final int MAX_AGGREGATION_AUTHORIZATIONS_LIMIT = 100;
|
||||
/** {@code AuthorizedAccountId} is modeled with {@code pattern: \d{12}}. */
|
||||
private static final Pattern AUTHORIZED_ACCOUNT_ID_PATTERN = Pattern.compile("\\d{12}");
|
||||
private static final int RULE_CONTRIBUTOR_CAP = 25;
|
||||
private static final int RESOURCE_CONTRIBUTOR_CAP = 100;
|
||||
|
||||
@@ -80,6 +86,8 @@ public class AwsConfigService {
|
||||
private Map<String, Map<String, ConfigRule>> configRules = new ConcurrentHashMap<>();
|
||||
// region -> packName -> pack (nested)
|
||||
private Map<String, Map<String, ConformancePack>> conformancePacks = new ConcurrentHashMap<>();
|
||||
// region -> authorizationKey("accountId|region") -> authorization (nested)
|
||||
private Map<String, Map<String, AggregationAuthorization>> aggregationAuthorizations = new ConcurrentHashMap<>();
|
||||
// region -> ruleName -> resourceKey("Type|Id") -> evaluation (doubly nested)
|
||||
private Map<String, Map<String, Map<String, ConfigEvaluation>>> evaluations = new ConcurrentHashMap<>();
|
||||
|
||||
@@ -120,6 +128,8 @@ public class AwsConfigService {
|
||||
new TypeReference<Map<String, Map<String, ConfigRule>>>() {});
|
||||
this.conformancePacks = storageBacked("config-conformance-packs.json",
|
||||
new TypeReference<Map<String, Map<String, ConformancePack>>>() {});
|
||||
this.aggregationAuthorizations = storageBacked("config-aggregation-authorizations.json",
|
||||
new TypeReference<Map<String, Map<String, AggregationAuthorization>>>() {});
|
||||
this.evaluations = storageBacked("config-evaluations.json",
|
||||
new TypeReference<Map<String, Map<String, Map<String, ConfigEvaluation>>>>() {});
|
||||
this.configurationRecorders = storageBacked("config-recorders.json",
|
||||
@@ -132,6 +142,7 @@ public class AwsConfigService {
|
||||
new TypeReference<Map<String, Map<String, String>>>() {});
|
||||
normalizeRegionMaps(configRules);
|
||||
normalizeRegionMaps(conformancePacks);
|
||||
normalizeRegionMaps(aggregationAuthorizations);
|
||||
normalizeRegionMaps(tags);
|
||||
normalizeEvaluationMaps();
|
||||
}
|
||||
@@ -878,6 +889,88 @@ public class AwsConfigService {
|
||||
return paginate(result, limit, nextToken, 20, 20, "InvalidLimitException");
|
||||
}
|
||||
|
||||
// --- Aggregation Authorizations ---
|
||||
|
||||
/** Put is an upsert, and request tags are applied at creation only. A Put that finds the
|
||||
* authorization already there ignores its Tags, leaving whatever TagResource/UntagResource
|
||||
* last set, so re-putting with a different tag set is not a way to retag.
|
||||
*
|
||||
* <p>The get-then-put runs under the same lock delete takes, because idempotency that is
|
||||
* only probable is not idempotency: two concurrent Puts for one account/Region would
|
||||
* otherwise both find nothing and both create, and the second would overwrite the first's
|
||||
* CreationTime and re-apply creation tags over a set TagResource may already have changed. */
|
||||
public AggregationAuthorization putAggregationAuthorization(String region, String authorizedAccountId,
|
||||
String authorizedAwsRegion, List<Map<String, String>> tagList) {
|
||||
requireAuthorizationKey(authorizedAccountId, authorizedAwsRegion);
|
||||
synchronized (lockFor(authorizationLockKey(region, authorizedAccountId, authorizedAwsRegion))) {
|
||||
Map<String, AggregationAuthorization> store = authorizationsFor(region);
|
||||
String key = authorizationKey(authorizedAccountId, authorizedAwsRegion);
|
||||
AggregationAuthorization existing = store.get(key);
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
}
|
||||
AggregationAuthorization authorization = new AggregationAuthorization(
|
||||
aggregationAuthorizationArn(region, authorizedAccountId, authorizedAwsRegion),
|
||||
authorizedAccountId, authorizedAwsRegion, now());
|
||||
store.put(key, authorization);
|
||||
persistRegion(aggregationAuthorizations, region);
|
||||
if (tagList != null && !tagList.isEmpty()) {
|
||||
tagResource(authorization.aggregationAuthorizationArn(), tagList);
|
||||
}
|
||||
return authorization;
|
||||
}
|
||||
}
|
||||
|
||||
public Paged<AggregationAuthorization> describeAggregationAuthorizations(String region, Integer limit,
|
||||
String nextToken) {
|
||||
Comparator<AggregationAuthorization> byAuthorizedTarget =
|
||||
Comparator.comparing(AggregationAuthorization::authorizedAccountId)
|
||||
.thenComparing(AggregationAuthorization::authorizedAwsRegion);
|
||||
List<AggregationAuthorization> result = new ArrayList<>(authorizationsFor(region).values());
|
||||
result.sort(byAuthorizedTarget);
|
||||
return paginate(result, limit, nextToken, MAX_AGGREGATION_AUTHORIZATIONS_LIMIT,
|
||||
MAX_AGGREGATION_AUTHORIZATIONS_LIMIT, "InvalidLimitException");
|
||||
}
|
||||
|
||||
/** The Config model declares no "not found" error for this operation, so deleting an
|
||||
* authorization that is not there succeeds. Only the parameters are validated.
|
||||
*
|
||||
* <p>The ARN is derived from the key rather than read off the removed entry, and its tags are
|
||||
* dropped whether or not an entry was there. Put reuses that same deterministic ARN, so a
|
||||
* delete that removed the authorization but did not reach the tags would otherwise leave them
|
||||
* to resurface on the next put, and the retry that should clean them up would find the
|
||||
* authorization already gone. */
|
||||
public void deleteAggregationAuthorization(String region, String authorizedAccountId,
|
||||
String authorizedAwsRegion) {
|
||||
requireAuthorizationKey(authorizedAccountId, authorizedAwsRegion);
|
||||
synchronized (lockFor(authorizationLockKey(region, authorizedAccountId, authorizedAwsRegion))) {
|
||||
Map<String, AggregationAuthorization> store = authorizationsFor(region);
|
||||
AggregationAuthorization removed =
|
||||
store.remove(authorizationKey(authorizedAccountId, authorizedAwsRegion));
|
||||
if (removed != null) {
|
||||
persistRegion(aggregationAuthorizations, region);
|
||||
}
|
||||
tags.remove(aggregationAuthorizationArn(region, authorizedAccountId, authorizedAwsRegion));
|
||||
}
|
||||
}
|
||||
|
||||
private String aggregationAuthorizationArn(String region, String authorizedAccountId,
|
||||
String authorizedAwsRegion) {
|
||||
return AwsArnUtils.Arn.of("config", region, regionResolver.getAccountId(),
|
||||
"aggregation-authorization/" + authorizedAccountId + "/" + authorizedAwsRegion).toString();
|
||||
}
|
||||
|
||||
private void requireAuthorizationKey(String authorizedAccountId, String authorizedAwsRegion) {
|
||||
if (isBlank(authorizedAccountId) || !AUTHORIZED_ACCOUNT_ID_PATTERN.matcher(authorizedAccountId).matches()) {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"AuthorizedAccountId must be a 12 digit AWS account ID.", 400);
|
||||
}
|
||||
if (isBlank(authorizedAwsRegion)) {
|
||||
throw new AwsException("InvalidParameterValueException",
|
||||
"AuthorizedAwsRegion must be specified.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Tagging ---
|
||||
|
||||
public void tagResource(String arn, List<Map<String, String>> tagList) {
|
||||
@@ -945,6 +1038,23 @@ public class AwsConfigService {
|
||||
return conformancePacks.computeIfAbsent(region, r -> new ConcurrentHashMap<>());
|
||||
}
|
||||
|
||||
private Map<String, AggregationAuthorization> authorizationsFor(String region) {
|
||||
return aggregationAuthorizations.computeIfAbsent(region, r -> new ConcurrentHashMap<>());
|
||||
}
|
||||
|
||||
private static String authorizationKey(String authorizedAccountId, String authorizedAwsRegion) {
|
||||
return authorizedAccountId + "|" + authorizedAwsRegion;
|
||||
}
|
||||
|
||||
/** Aggregation authorizations share {@link #ruleLocks} with the config rules, so their keys
|
||||
* are namespaced apart. A config rule name cannot contain '|', but making the two key spaces
|
||||
* disjoint by construction costs nothing and does not depend on that staying true. */
|
||||
private static String authorizationLockKey(String region, String authorizedAccountId,
|
||||
String authorizedAwsRegion) {
|
||||
return "aggregation-authorization|" + region + "|"
|
||||
+ authorizationKey(authorizedAccountId, authorizedAwsRegion);
|
||||
}
|
||||
|
||||
private Map<String, Map<String, ConfigEvaluation>> evaluationsFor(String region) {
|
||||
return evaluations.computeIfAbsent(region, r -> new ConcurrentHashMap<>());
|
||||
}
|
||||
|
||||
+38
-5
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.configservice;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.services.configservice.model.AggregationAuthorization;
|
||||
import io.github.hectorvent.floci.services.configservice.model.ConfigEvaluation;
|
||||
import io.github.hectorvent.floci.services.configservice.model.ConfigRule;
|
||||
import io.github.hectorvent.floci.services.configservice.model.ConfigurationRecorder;
|
||||
@@ -63,6 +64,9 @@ public class ConfigServiceJsonHandler {
|
||||
case "PutRetentionConfiguration" -> putRetentionConfiguration(request, region);
|
||||
case "DescribeRetentionConfigurations" -> describeRetentionConfigurations(request, region);
|
||||
case "DeleteRetentionConfiguration" -> deleteRetentionConfiguration(request, region);
|
||||
case "PutAggregationAuthorization" -> putAggregationAuthorization(request, region);
|
||||
case "DescribeAggregationAuthorizations" -> describeAggregationAuthorizations(request, region);
|
||||
case "DeleteAggregationAuthorization" -> deleteAggregationAuthorization(request, region);
|
||||
case "TagResource" -> tagResource(request);
|
||||
case "UntagResource" -> untagResource(request);
|
||||
case "ListTagsForResource" -> listTagsForResource(request);
|
||||
@@ -299,15 +303,36 @@ public class ConfigServiceJsonHandler {
|
||||
return Response.ok(pagedResponse("ConformancePackStatusDetails", page)).build();
|
||||
}
|
||||
|
||||
// --- Aggregation Authorizations ---
|
||||
|
||||
private Response putAggregationAuthorization(JsonNode req, String region) {
|
||||
AggregationAuthorization authorization = service.putAggregationAuthorization(region,
|
||||
req.path("AuthorizedAccountId").asText(null),
|
||||
req.path("AuthorizedAwsRegion").asText(null),
|
||||
extractTags(req));
|
||||
ObjectNode resp = mapper.createObjectNode();
|
||||
resp.set("AggregationAuthorization", mapper.valueToTree(authorization));
|
||||
return Response.ok(resp).build();
|
||||
}
|
||||
|
||||
private Response describeAggregationAuthorizations(JsonNode req, String region) {
|
||||
AwsConfigService.Paged<AggregationAuthorization> page = service.describeAggregationAuthorizations(region,
|
||||
extractLimit(req, "Limit"), extractNextToken(req));
|
||||
return Response.ok(pagedResponse("AggregationAuthorizations", page)).build();
|
||||
}
|
||||
|
||||
private Response deleteAggregationAuthorization(JsonNode req, String region) {
|
||||
service.deleteAggregationAuthorization(region,
|
||||
req.path("AuthorizedAccountId").asText(null),
|
||||
req.path("AuthorizedAwsRegion").asText(null));
|
||||
return Response.ok(mapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
// --- Tagging ---
|
||||
|
||||
private Response tagResource(JsonNode req) {
|
||||
String arn = req.path("ResourceArn").asText(null);
|
||||
List<Map<String, String>> tagList = new ArrayList<>();
|
||||
req.path("Tags").forEach(t -> tagList.add(Map.of(
|
||||
"Key", t.path("Key").asText(),
|
||||
"Value", t.path("Value").asText())));
|
||||
service.tagResource(arn, tagList);
|
||||
service.tagResource(arn, extractTags(req));
|
||||
return Response.ok(mapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
@@ -329,6 +354,14 @@ public class ConfigServiceJsonHandler {
|
||||
|
||||
// --- Helpers ---
|
||||
|
||||
private List<Map<String, String>> extractTags(JsonNode req) {
|
||||
List<Map<String, String>> tagList = new ArrayList<>();
|
||||
req.path("Tags").forEach(t -> tagList.add(Map.of(
|
||||
"Key", t.path("Key").asText(),
|
||||
"Value", t.path("Value").asText())));
|
||||
return tagList;
|
||||
}
|
||||
|
||||
private List<String> extractStringList(JsonNode req, String fieldName) {
|
||||
List<String> result = new ArrayList<>();
|
||||
if (req.has(fieldName)) {
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package io.github.hectorvent.floci.services.configservice.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record AggregationAuthorization(
|
||||
@JsonProperty("AggregationAuthorizationArn") String aggregationAuthorizationArn,
|
||||
@JsonProperty("AuthorizedAccountId") String authorizedAccountId,
|
||||
@JsonProperty("AuthorizedAwsRegion") String authorizedAwsRegion,
|
||||
@JsonProperty("CreationTime") Long creationTime) {
|
||||
}
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
package io.github.hectorvent.floci.services.configservice;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class AggregationAuthorizationIntegrationTest {
|
||||
|
||||
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static final String TARGET_PREFIX = "StarlingDoveService.";
|
||||
private static final String AUTHORIZED_ACCOUNT = "111122223333";
|
||||
private static final String AUTHORIZED_REGION = "eu-west-1";
|
||||
private static final String MATCHING = "AggregationAuthorizations.findAll { it.AuthorizedAccountId == '"
|
||||
+ AUTHORIZED_ACCOUNT + "' && it.AuthorizedAwsRegion == '" + AUTHORIZED_REGION + "' }";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
private static io.restassured.response.Response call(String action, String body) {
|
||||
return given()
|
||||
.header("X-Amz-Target", TARGET_PREFIX + action)
|
||||
.contentType(CONTENT_TYPE)
|
||||
.body(body)
|
||||
.when()
|
||||
.post("/");
|
||||
}
|
||||
|
||||
private static String authorizationBody() {
|
||||
return """
|
||||
{
|
||||
"AuthorizedAccountId": "%s",
|
||||
"AuthorizedAwsRegion": "%s"
|
||||
}
|
||||
""".formatted(AUTHORIZED_ACCOUNT, AUTHORIZED_REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void putAggregationAuthorization() {
|
||||
call("PutAggregationAuthorization", """
|
||||
{
|
||||
"AuthorizedAccountId": "%s",
|
||||
"AuthorizedAwsRegion": "%s",
|
||||
"Tags": [{"Key": "env", "Value": "prod"}]
|
||||
}
|
||||
""".formatted(AUTHORIZED_ACCOUNT, AUTHORIZED_REGION))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("AggregationAuthorization.AggregationAuthorizationArn",
|
||||
allOf(startsWith("arn:aws:config:"),
|
||||
endsWith(":aggregation-authorization/" + AUTHORIZED_ACCOUNT + "/" + AUTHORIZED_REGION)))
|
||||
.body("AggregationAuthorization.AuthorizedAccountId", equalTo(AUTHORIZED_ACCOUNT))
|
||||
.body("AggregationAuthorization.AuthorizedAwsRegion", equalTo(AUTHORIZED_REGION))
|
||||
.body("AggregationAuthorization.CreationTime", notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void putAggregationAuthorizationIsIdempotent() {
|
||||
String arn = call("PutAggregationAuthorization", authorizationBody())
|
||||
.then().statusCode(200)
|
||||
.extract().path("AggregationAuthorization.AggregationAuthorizationArn");
|
||||
|
||||
call("DescribeAggregationAuthorizations", "{}")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(MATCHING, hasSize(1))
|
||||
.body(MATCHING + ".AggregationAuthorizationArn", contains(arn));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void describeAggregationAuthorizationsListsTheAuthorization() {
|
||||
call("DescribeAggregationAuthorizations", "{}")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(MATCHING, hasSize(1))
|
||||
.body(MATCHING + "[0].CreationTime", notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void tagsSuppliedOnPutAreVisibleToListTagsForResource() {
|
||||
String arn = call("DescribeAggregationAuthorizations", "{}")
|
||||
.then().statusCode(200)
|
||||
.extract().<String>path(MATCHING + "[0].AggregationAuthorizationArn");
|
||||
|
||||
call("ListTagsForResource", "{\"ResourceArn\": \"" + arn + "\"}")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Tags", hasSize(1))
|
||||
.body("Tags[0].Key", equalTo("env"))
|
||||
.body("Tags[0].Value", equalTo("prod"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void rePutIgnoresItsTagsAndTheTaggingApiStillWorks() {
|
||||
String arn = call("DescribeAggregationAuthorizations", "{}")
|
||||
.then().statusCode(200)
|
||||
.extract().<String>path(MATCHING + "[0].AggregationAuthorizationArn");
|
||||
String listTags = "{\"ResourceArn\": \"" + arn + "\"}";
|
||||
|
||||
call("PutAggregationAuthorization", """
|
||||
{
|
||||
"AuthorizedAccountId": "%s",
|
||||
"AuthorizedAwsRegion": "%s",
|
||||
"Tags": [{"Key": "env", "Value": "dev"}, {"Key": "tier", "Value": "gold"}]
|
||||
}
|
||||
""".formatted(AUTHORIZED_ACCOUNT, AUTHORIZED_REGION))
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
call("ListTagsForResource", listTags)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Tags", hasSize(1))
|
||||
.body("Tags[0].Key", equalTo("env"))
|
||||
.body("Tags[0].Value", equalTo("prod"));
|
||||
|
||||
call("TagResource", """
|
||||
{"ResourceArn": "%s", "Tags": [{"Key": "tier", "Value": "gold"}]}
|
||||
""".formatted(arn))
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
call("ListTagsForResource", listTags)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Tags.Key", containsInAnyOrder("env", "tier"));
|
||||
|
||||
call("UntagResource", """
|
||||
{"ResourceArn": "%s", "TagKeys": ["tier"]}
|
||||
""".formatted(arn))
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
call("ListTagsForResource", listTags)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Tags.Key", contains("env"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void deleteAggregationAuthorization() {
|
||||
call("DeleteAggregationAuthorization", authorizationBody())
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
call("DescribeAggregationAuthorizations", "{}")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(MATCHING, empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void deleteNonexistentAggregationAuthorizationSucceeds() {
|
||||
call("DeleteAggregationAuthorization", authorizationBody())
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(8)
|
||||
void putRejectsAnAccountIdThatIsNotTwelveDigits() {
|
||||
call("PutAggregationAuthorization", """
|
||||
{"AuthorizedAccountId": "12345", "AuthorizedAwsRegion": "eu-west-1"}
|
||||
""")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterValueException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(9)
|
||||
void unrelatedActionsStillReportInvalidAction() {
|
||||
call("PutAggregationAuthorizations", authorizationBody())
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidAction"));
|
||||
}
|
||||
}
|
||||
+339
@@ -0,0 +1,339 @@
|
||||
package io.github.hectorvent.floci.services.configservice;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.configservice.model.AggregationAuthorization;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.CyclicBarrier;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* AggregationAuthorization is keyed by (AuthorizedAccountId, AuthorizedAwsRegion). Put is an
|
||||
* upsert, and the Config model declares no "not found" error for DeleteAggregationAuthorization,
|
||||
* so deleting one that is absent succeeds.
|
||||
*/
|
||||
class AwsConfigServiceAggregationAuthorizationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String AUTHORIZED_ACCOUNT = "111122223333";
|
||||
|
||||
private AwsConfigService service() {
|
||||
return new AwsConfigService(new RegionResolver(REGION, ACCOUNT), null);
|
||||
}
|
||||
|
||||
private List<AggregationAuthorization> authorizations(AwsConfigService service, String region) {
|
||||
return service.describeAggregationAuthorizations(region, null, null).items();
|
||||
}
|
||||
|
||||
@Test
|
||||
void putReturnsAnArnAndCreationTime() {
|
||||
AwsConfigService service = service();
|
||||
|
||||
AggregationAuthorization created =
|
||||
service.putAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "eu-west-1", null);
|
||||
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(created.aggregationAuthorizationArn());
|
||||
assertEquals("aws", arn.partition());
|
||||
assertEquals("config", arn.service());
|
||||
assertEquals(REGION, arn.region());
|
||||
assertEquals(ACCOUNT, arn.accountId());
|
||||
assertEquals("aggregation-authorization/" + AUTHORIZED_ACCOUNT + "/eu-west-1", arn.resource());
|
||||
assertEquals(AUTHORIZED_ACCOUNT, created.authorizedAccountId());
|
||||
assertEquals("eu-west-1", created.authorizedAwsRegion());
|
||||
assertNotNull(created.creationTime(), "CreationTime must be populated");
|
||||
}
|
||||
|
||||
@Test
|
||||
void putIsIdempotentForTheSameAccountAndRegion() {
|
||||
AwsConfigService service = service();
|
||||
|
||||
AggregationAuthorization first =
|
||||
service.putAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "eu-west-1", null);
|
||||
AggregationAuthorization second =
|
||||
service.putAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "eu-west-1", null);
|
||||
|
||||
assertEquals(first.aggregationAuthorizationArn(), second.aggregationAuthorizationArn());
|
||||
assertEquals(first.creationTime(), second.creationTime(),
|
||||
"re-authorizing must not restart the creation time");
|
||||
assertEquals(1, authorizations(service, REGION).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeListsEveryAuthorizationSortedByAccountThenRegion() {
|
||||
AwsConfigService service = service();
|
||||
service.putAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "eu-west-1", null);
|
||||
service.putAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "ap-south-1", null);
|
||||
service.putAggregationAuthorization(REGION, "444455556666", "eu-west-1", null);
|
||||
|
||||
List<AggregationAuthorization> listed = authorizations(service, REGION);
|
||||
|
||||
assertEquals(List.of(
|
||||
AUTHORIZED_ACCOUNT + "|ap-south-1",
|
||||
AUTHORIZED_ACCOUNT + "|eu-west-1",
|
||||
"444455556666|eu-west-1"),
|
||||
listed.stream()
|
||||
.map(a -> a.authorizedAccountId() + "|" + a.authorizedAwsRegion())
|
||||
.toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeIsScopedToTheRequestRegion() {
|
||||
AwsConfigService service = service();
|
||||
service.putAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "eu-west-1", null);
|
||||
|
||||
assertEquals(1, authorizations(service, REGION).size());
|
||||
assertTrue(authorizations(service, "eu-central-1").isEmpty(),
|
||||
"an authorization must not leak into another region's aggregator");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRemovesOnlyTheNamedAuthorization() {
|
||||
AwsConfigService service = service();
|
||||
service.putAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "eu-west-1", null);
|
||||
service.putAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "ap-south-1", null);
|
||||
|
||||
service.deleteAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "eu-west-1");
|
||||
|
||||
assertEquals(List.of("ap-south-1"),
|
||||
authorizations(service, REGION).stream()
|
||||
.map(AggregationAuthorization::authorizedAwsRegion).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingAnAbsentAuthorizationSucceeds() {
|
||||
AwsConfigService service = service();
|
||||
|
||||
assertDoesNotThrow(() -> service.deleteAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "eu-west-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteClearsTagsEvenWhenTheAuthorizationIsAlreadyGone() {
|
||||
AwsConfigService service = service();
|
||||
String arn = service.putAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "eu-west-1", null)
|
||||
.aggregationAuthorizationArn();
|
||||
|
||||
// An interrupted delete leaves the entry removed but its tags behind. Reproduce that
|
||||
// state, then retry the delete: the retry must still reach the tags.
|
||||
service.deleteAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "eu-west-1");
|
||||
service.tagResource(arn, List.of(Map.of("Key", "env", "Value", "prod")));
|
||||
assertTrue(authorizations(service, REGION).isEmpty(), "precondition: the entry is gone");
|
||||
|
||||
service.deleteAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "eu-west-1");
|
||||
|
||||
assertTrue(service.listTagsForResource(arn).isEmpty(),
|
||||
"a retried delete must clear tags an interrupted attempt left on the ARN");
|
||||
assertEquals(arn,
|
||||
service.putAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "eu-west-1", null)
|
||||
.aggregationAuthorizationArn(),
|
||||
"put reuses the same deterministic ARN, which is why the stale tags mattered");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagsSuppliedOnPutAreReadableThroughListTagsForResource() {
|
||||
AwsConfigService service = service();
|
||||
|
||||
AggregationAuthorization created = service.putAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT,
|
||||
"eu-west-1", List.of(Map.of("Key", "env", "Value", "prod")));
|
||||
|
||||
List<Map<String, String>> tags = service.listTagsForResource(created.aggregationAuthorizationArn());
|
||||
assertEquals(List.of(Map.of("Key", "env", "Value", "prod")), tags);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rePutIgnoresItsTagsAndLeavesTheCreationTagsInPlace() {
|
||||
AwsConfigService service = service();
|
||||
String arn = service.putAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "eu-west-1",
|
||||
List.of(Map.of("Key", "env", "Value", "prod"),
|
||||
Map.of("Key", "owner", "Value", "platform")))
|
||||
.aggregationAuthorizationArn();
|
||||
|
||||
service.putAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "eu-west-1",
|
||||
List.of(Map.of("Key", "env", "Value", "dev"),
|
||||
Map.of("Key", "tier", "Value", "gold")));
|
||||
|
||||
assertEquals(Map.of("env", "prod", "owner", "platform"), tagMap(service, arn),
|
||||
"a put that finds the authorization already there must ignore its Tags: "
|
||||
+ "no overwrite of env, and no tier added");
|
||||
|
||||
// Tags do change through the tagging API, which is the only way AWS offers.
|
||||
service.tagResource(arn, List.of(Map.of("Key", "env", "Value", "dev")));
|
||||
assertEquals(Map.of("env", "dev", "owner", "platform"), tagMap(service, arn),
|
||||
"TagResource must still update an existing tag");
|
||||
|
||||
service.untagResource(arn, List.of("owner"));
|
||||
assertEquals(Map.of("env", "dev"), tagMap(service, arn),
|
||||
"UntagResource must still remove a tag");
|
||||
}
|
||||
|
||||
private Map<String, String> tagMap(AwsConfigService service, String arn) {
|
||||
return service.listTagsForResource(arn).stream()
|
||||
.collect(Collectors.toMap(t -> t.get("Key"), t -> t.get("Value")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteDropsTheAuthorizationTagsSoARecreateStartsClean() {
|
||||
AwsConfigService service = service();
|
||||
AggregationAuthorization created = service.putAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT,
|
||||
"eu-west-1", List.of(Map.of("Key", "env", "Value", "prod")));
|
||||
|
||||
service.deleteAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "eu-west-1");
|
||||
service.putAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "eu-west-1", null);
|
||||
|
||||
assertTrue(service.listTagsForResource(created.aggregationAuthorizationArn()).isEmpty(),
|
||||
"tags of a deleted authorization must not resurface on the reused ARN");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAnAccountIdThatIsNotTwelveDigits() {
|
||||
AwsConfigService service = service();
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.putAggregationAuthorization(REGION, "12345", "eu-west-1", null));
|
||||
assertEquals("InvalidParameterValueException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAMissingAuthorizedRegion() {
|
||||
AwsConfigService service = service();
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.putAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, " ", null));
|
||||
assertEquals("InvalidParameterValueException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsALimitAboveTheModeledMaximum() {
|
||||
AwsConfigService service = service();
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.describeAggregationAuthorizations(REGION, 101, null));
|
||||
assertEquals("InvalidLimitException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describePaginatesWithNextToken() {
|
||||
AwsConfigService service = service();
|
||||
service.putAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "eu-west-1", null);
|
||||
service.putAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "ap-south-1", null);
|
||||
|
||||
AwsConfigService.Paged<AggregationAuthorization> first =
|
||||
service.describeAggregationAuthorizations(REGION, 1, null);
|
||||
assertEquals(1, first.items().size());
|
||||
assertNotNull(first.nextToken());
|
||||
|
||||
AwsConfigService.Paged<AggregationAuthorization> second =
|
||||
service.describeAggregationAuthorizations(REGION, 1, first.nextToken());
|
||||
assertEquals(1, second.items().size());
|
||||
assertNull(second.nextToken());
|
||||
assertEquals("eu-west-1", second.items().getFirst().authorizedAwsRegion());
|
||||
}
|
||||
|
||||
/**
|
||||
* Idempotency that only usually holds is not idempotency. Put is a get-then-put, so without a
|
||||
* lock two concurrent Puts for one (account, Region) both find nothing and both create, and
|
||||
* the loser's caller is handed an object the store no longer contains.
|
||||
*
|
||||
* <p>Reference identity is the assertion that catches this, and the obvious alternatives do
|
||||
* not: the store is keyed on the pair so its size is 1 either way, the ARN is derived from the
|
||||
* key so it is equal either way, and CreationTime is epoch seconds so a racing pair created
|
||||
* inside one second is indistinguishable by timestamp too.
|
||||
*
|
||||
* <p>Many short rounds rather than one wide one: the unlocked window is a few instructions, so
|
||||
* what makes the race land is repeated fresh starts, not more threads on one start.
|
||||
*/
|
||||
@Test
|
||||
void concurrentPutsForOneKeyAllReturnTheStoredAuthorization() throws Exception {
|
||||
int rounds = 300;
|
||||
int threads = 4;
|
||||
ExecutorService pool = Executors.newFixedThreadPool(threads);
|
||||
try {
|
||||
int mismatches = 0;
|
||||
for (int round = 0; round < rounds; round++) {
|
||||
AwsConfigService service = service();
|
||||
CyclicBarrier gate = new CyclicBarrier(threads);
|
||||
List<Future<AggregationAuthorization>> futures = new ArrayList<>();
|
||||
for (int i = 0; i < threads; i++) {
|
||||
futures.add(pool.submit(() -> {
|
||||
gate.await(10, TimeUnit.SECONDS);
|
||||
return service.putAggregationAuthorization(
|
||||
REGION, AUTHORIZED_ACCOUNT, "eu-west-1", null);
|
||||
}));
|
||||
}
|
||||
List<AggregationAuthorization> returned = new ArrayList<>();
|
||||
for (Future<AggregationAuthorization> future : futures) {
|
||||
returned.add(future.get(10, TimeUnit.SECONDS));
|
||||
}
|
||||
List<AggregationAuthorization> stored = authorizations(service, REGION);
|
||||
assertEquals(1, stored.size());
|
||||
for (AggregationAuthorization each : returned) {
|
||||
if (each != stored.getFirst()) {
|
||||
mismatches++;
|
||||
}
|
||||
}
|
||||
}
|
||||
assertEquals(0, mismatches,
|
||||
"a concurrent Put returned an authorization the store does not hold");
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
assertTrue(pool.awaitTermination(10, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
/** Delete takes the same lock, so it cannot interleave with the create half of a Put. */
|
||||
@Test
|
||||
void concurrentPutAndDeleteLeaveNoHalfState() throws Exception {
|
||||
AwsConfigService service = service();
|
||||
ExecutorService pool = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
for (int round = 0; round < 50; round++) {
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
Future<?> put = pool.submit(() -> {
|
||||
start.await();
|
||||
return service.putAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "eu-west-1", null);
|
||||
});
|
||||
Future<?> delete = pool.submit(() -> {
|
||||
start.await();
|
||||
service.deleteAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "eu-west-1");
|
||||
return null;
|
||||
});
|
||||
start.countDown();
|
||||
put.get(10, TimeUnit.SECONDS);
|
||||
delete.get(10, TimeUnit.SECONDS);
|
||||
|
||||
// Either order is legal; what is not legal is an entry whose tags outlived a delete.
|
||||
List<AggregationAuthorization> after = authorizations(service, REGION);
|
||||
assertTrue(after.size() <= 1);
|
||||
if (after.isEmpty()) {
|
||||
assertTrue(service.listTagsForResource(
|
||||
AwsArnUtils.Arn.of("config", REGION, ACCOUNT,
|
||||
"aggregation-authorization/" + AUTHORIZED_ACCOUNT + "/eu-west-1").toString())
|
||||
.isEmpty(), "delete left tags behind for a removed authorization");
|
||||
}
|
||||
service.deleteAggregationAuthorization(REGION, AUTHORIZED_ACCOUNT, "eu-west-1");
|
||||
}
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
assertTrue(pool.awaitTermination(10, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user