feat(config): compliance evaluation loop, retention, pagination (#2642)

* feat(config): add compliance evaluation loop, retention, and pagination

Replace the hardcoded INSUFFICIENT_DATA compliance with real aggregation
over evaluations reported via PutEvaluations / PutExternalEvaluation:

- New actions (13): PutEvaluations, PutExternalEvaluation,
  DeleteEvaluationResults, DescribeComplianceByResource,
  GetComplianceDetailsByConfigRule, GetComplianceDetailsByResource,
  GetComplianceSummaryByConfigRule, GetComplianceSummaryByResourceType,
  DeleteConfigurationRecorder, DeleteDeliveryChannel,
  PutRetentionConfiguration, DescribeRetentionConfigurations,
  DeleteRetentionConfiguration
- PutConfigRule now round-trips the full AWS rule shape (Description,
  Scope, SourceDetails, InputParameters, MaximumExecutionFrequency,
  EvaluationModes) instead of silently dropping fields
- Evaluations persist to config-evaluations.json and are cascade-deleted
  with their rule; retention persists to config-retention.json
- NextToken/Limit pagination on describe/get operations with AWS page
  sizes and InvalidNextTokenException/InvalidLimitException validation
- DescribeConfigRules with an unknown name now fails with
  NoSuchConfigRuleException, matching AWS
- boto3 compatibility suite: tests/test_config.py

Since Floci performs no Lambda invocation, PutEvaluations accepts the
config rule name as the ResultToken; documented in the service doc's
deviations section.

* fix: honor Limit field in Config pagination requests

* fix(config): enforce the modeled rule enums and the ComplianceTypes filter shape

PutConfigRule now deserializes the whole modeled ConfigRule and stores it, so
Source.Owner, MaximumExecutionFrequency, ConfigRuleState and
EvaluationModes[].Mode were persisted and echoed back verbatim — a rule AWS
would have rejected with InvalidParameterValueException read back as a valid
one.

The ComplianceTypes filter on the four compliance reads was likewise unchecked:
an unmodeled value or a list longer than the shape's max of 3 simply matched
nothing, which a caller reads as an empty result rather than as a rejection.

* fix(config): validate the nested SourceDetails enums and Scope cardinality

The stored ConfigRule carries SourceDetails, whose EventSource (aws.config only),
MessageType and MaximumExecutionFrequency are all enum-typed, and a Scope whose
ComplianceResourceTypes list is capped at 100. All four were persisted and echoed
back by DescribeConfigRules verbatim, one level below the members the previous
commit checked.

* fix(config): reject a missing ConfigRuleName on DeleteConfigRule

store.remove(ruleName) throws NullPointerException on the backing
ConcurrentHashMap when ruleName is null (the handler passes null when
ConfigRuleName is absent from the request), producing a 500 instead of
the modeled NoSuchConfigRuleException. Guard on isBlank(ruleName)
first, matching the existing requireRule() idiom used by the sibling
evaluation operations for the same field.

* fix(config): keep the newest evaluation when PutEvaluations reorders

storeEvaluations() unconditionally overwrote the stored compliance
result for a resource/rule pair, so an older evaluation arriving after
a newer one (e.g. an out-of-order Lambda invocation) regressed
compliance details, aggregates, and summaries back to the stale value.
Compare against the stored OrderingTimestamp and skip the incoming
evaluation when it is older than what is already recorded.

* fix(config): make PutEvaluations atomic per resource/rule key

storeEvaluations() read the current evaluation with a plain get() and
wrote the new one with a separate put(), so two concurrent
PutEvaluations calls for the same resource could both read the old
value before either wrote, letting an older OrderingTimestamp win the
race regardless of arrival order. Replace the read-then-write with
ConcurrentHashMap.compute(), which is atomic per key.

Added a stress test exercising 16 concurrent writers per resource key
across 100 attempts; it passes reliably under the fix. The race window
in the prior get/put shape is narrow enough (a handful of nanoseconds
between the two calls) that it did not reproduce deterministically
under test scheduling even with that much contention -- the fix is
justified by the non-atomic read-then-write shape itself, not by a
forced failure.

* fix(config): enforce DescribeConfigRules' 25-name limit

ConfigRuleNames is modeled with Maximum 25 items (confirmed against
botocore's config service-2.json) but describeConfigRules had no size
check, so 26+ names were processed instead of rejected with
InvalidParameterValueException like every other array-size limit this
PR already enforces.

* fix(config): close the DeleteConfigRule/PutEvaluations deletion race

PutEvaluations (and PutExternalEvaluation, DeleteEvaluationResults)
checked a rule's existence via requireRule and then wrote to the
evaluations map as two separate steps. If DeleteConfigRule ran in
between -- removing the rule and its evaluation bucket -- the pending
PutEvaluations call would recreate the bucket via computeIfAbsent
after the delete, orphaning evaluations under the deleted rule's name.
A later rule created with that same name would then inherit the
deleted rule's compliance details and evaluation status.

Guard the check-then-act with a per-rule monitor (ruleKey(region,
ruleName)), matching the lockFor()-keyed-monitor idiom already used by
DocDbService for the identical class of race between a tag update and
a delete.

Added a stress test racing PutEvaluations against DeleteConfigRule
across 200 attempts, then recreating the rule under the same name and
asserting a clean (INSUFFICIENT_DATA) evaluation state. It passes
under the fix; as with the earlier PutEvaluations-ordering race, it
did not reproduce RED against the pre-fix code even under that much
contention -- the race window between the existence check and the map
write is too narrow to hit deterministically without injecting an
artificial delay into production code. The fix is justified by the
non-atomic check-then-act shape itself, confirmed by reading the code.
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-08-28 11:58:39 -04:00
1 parent 41b5148824
commit 1b3417a7a3
33 files changed
+2970 -125

No files matched your search

@@ -0,0 +1,147 @@
package io.github.hectorvent.floci.services.configservice;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
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.ConfigRuleSource;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* PutEvaluations for the same resource/rule pair must not let an older evaluation win a race
* against a newer one. A separate get-then-put is not atomic on the backing ConcurrentHashMap:
* both calls can read the current value before either writes, so whichever write lands last wins
* regardless of OrderingTimestamp.
*/
class AwsConfigServiceEvaluationConcurrencyTest {
private static final String REGION = "us-east-1";
@Test
void concurrentEvaluationsForTheSameResourceKeepTheNewerOrderingTimestamp() throws Exception {
AwsConfigService service = new AwsConfigService(new RegionResolver(REGION, "000000000000"), null);
service.putConfigRule(REGION, new ConfigRule("race-rule", null, null, null, null,
new ConfigRuleSource("CUSTOM_LAMBDA", "arn:aws:lambda:us-east-1:000000000000:function:check",
null, null),
null, null, null, null, null));
int threadsPerAttempt = 16;
for (int attempt = 0; attempt < 100; attempt++) {
String resourceId = "bucket-" + attempt;
CountDownLatch start = new CountDownLatch(1);
AtomicReference<Throwable> unexpected = new AtomicReference<>();
List<Thread> writers = new java.util.ArrayList<>();
// Every writer races on the SAME resource key; only the last one in should win, and
// by OrderingTimestamp rather than by write order. Half submit an older evaluation,
// half a newer one, so any interleaving that lets an older write land last is a bug.
for (int i = 0; i < threadsPerAttempt; i++) {
boolean isNewer = i % 2 == 0;
Thread writer = new Thread(() -> {
await(start);
try {
service.putEvaluations(REGION, "race-rule",
List.of(evaluation(resourceId, isNewer ? "COMPLIANT" : "NON_COMPLIANT",
isNewer ? 1700000001.0 : 1700000000.0)), false);
} catch (Throwable t) {
unexpected.set(t);
}
});
writers.add(writer);
writer.start();
}
start.countDown();
for (Thread writer : writers) {
writer.join(TimeUnit.SECONDS.toMillis(10));
assertFalse(writer.isAlive(), "a PutEvaluations call never finished");
}
assertNull(unexpected.get(), () -> "unexpected failure: " + unexpected.get());
String recorded = service.getComplianceDetailsByResource(REGION, "AWS::S3::Bucket", resourceId,
null, null).items().getFirst().complianceType();
assertEquals("COMPLIANT", recorded,
"attempt " + attempt + ": the newer evaluation must win regardless of write order");
}
}
@Test
void deletingARuleDuringPutEvaluationsDoesNotLeaveEvaluationsForAFutureSameNamedRule() throws Exception {
AwsConfigService service = new AwsConfigService(new RegionResolver(REGION, "000000000000"), null);
ConfigRuleSource source = new ConfigRuleSource("CUSTOM_LAMBDA",
"arn:aws:lambda:us-east-1:000000000000:function:check", null, null);
for (int attempt = 0; attempt < 200; attempt++) {
String ruleName = "race-rule-" + attempt;
service.putConfigRule(REGION, new ConfigRule(ruleName, null, null, null, null, source,
null, null, null, null, null));
CountDownLatch start = new CountDownLatch(1);
AtomicReference<Throwable> putFailure = new AtomicReference<>();
AtomicReference<Throwable> deleteFailure = new AtomicReference<>();
Thread putter = new Thread(() -> {
await(start);
try {
service.putEvaluations(REGION, ruleName,
List.of(evaluation("bucket-1", "NON_COMPLIANT", 1700000000.0)), false);
} catch (Throwable t) {
putFailure.set(t);
}
});
Thread deleter = new Thread(() -> {
await(start);
try {
service.deleteConfigRule(REGION, ruleName);
} catch (Throwable t) {
deleteFailure.set(t);
}
});
putter.start();
deleter.start();
start.countDown();
putter.join(TimeUnit.SECONDS.toMillis(10));
deleter.join(TimeUnit.SECONDS.toMillis(10));
assertFalse(putter.isAlive() || deleter.isAlive(), "a putEvaluations/deleteConfigRule call never finished");
// Losing the race to the delete (NoSuchConfigRuleException) is a legitimate outcome for
// the putter; any other failure, on either side, is not.
if (putFailure.get() != null) {
assertEquals("NoSuchConfigRuleException",
((AwsException) putFailure.get()).getErrorCode(),
"unexpected putEvaluations failure: " + putFailure.get());
}
assertNull(deleteFailure.get(), () -> "unexpected deleteConfigRule failure: " + deleteFailure.get());
// A brand new rule reusing the deleted rule's name must start with a clean evaluation
// bucket -- it must never inherit compliance details left behind by the deleted rule.
service.putConfigRule(REGION, new ConfigRule(ruleName, null, null, null, null, source,
null, null, null, null, null));
assertEquals("INSUFFICIENT_DATA", service.complianceForRule(REGION, ruleName).complianceType(),
"attempt " + attempt + ": a same-named rule inherited the deleted rule's evaluations");
}
}
private static ConfigEvaluation evaluation(String resourceId, String complianceType, double orderingTimestamp) {
return new ConfigEvaluation("AWS::S3::Bucket", resourceId, complianceType, null,
orderingTimestamp, null, null);
}
private static void await(CountDownLatch latch) {
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
}
}
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
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.ConfigRuleSource;
import io.github.hectorvent.floci.services.configservice.model.ConfigurationRecorder;
@@ -33,8 +34,8 @@ class AwsConfigServicePersistenceTest {
SharedStorageFactory storage = new SharedStorageFactory();
AwsConfigService first = serviceWithStorage(storage);
ConfigRule rule = first.putConfigRule(REGION, "s3-public-read",
new ConfigRuleSource("AWS", "S3_BUCKET_PUBLIC_READ_PROHIBITED"));
ConfigRule rule = first.putConfigRule(REGION,
rule("s3-public-read", "AWS", "S3_BUCKET_PUBLIC_READ_PROHIBITED"));
first.putConformancePack(REGION, "ops-pack", "s3://bucket/template.yaml", null);
first.putConfigurationRecorder(REGION, new ConfigurationRecorder("default",
"arn:aws:iam::000000000000:role/config", new RecordingGroup(true, false, null)));
@@ -61,9 +62,8 @@ class AwsConfigServicePersistenceTest {
SharedStorageFactory storage = new SharedStorageFactory();
AwsConfigService first = serviceWithStorage(storage);
ConfigRule rule = first.putConfigRule(REGION, "keep",
new ConfigRuleSource("AWS", "REQUIRED_TAGS"));
first.putConfigRule(REGION, "drop", new ConfigRuleSource("AWS", "REQUIRED_TAGS"));
ConfigRule rule = first.putConfigRule(REGION, rule("keep", "AWS", "REQUIRED_TAGS"));
first.putConfigRule(REGION, rule("drop", "AWS", "REQUIRED_TAGS"));
first.deleteConfigRule(REGION, "drop");
first.tagResource(rule.configRuleArn(),
List.of(Map.of("Key", "env", "Value", "prod"), Map.of("Key", "team", "Value", "sec")));
@@ -79,6 +79,66 @@ class AwsConfigServicePersistenceTest {
assertTrue(!tags.containsKey("team"), "untagged key must not reappear after restart");
}
@Test
void evaluationsSurviveRestart() {
SharedStorageFactory storage = new SharedStorageFactory();
AwsConfigService first = serviceWithStorage(storage);
first.putConfigRule(REGION, rule("bucket-policy", "CUSTOM_LAMBDA",
"arn:aws:lambda:us-east-1:000000000000:function:check"));
first.putEvaluations(REGION, "bucket-policy",
List.of(evaluation("AWS::S3::Bucket", "bucket-1", "NON_COMPLIANT")), false);
AwsConfigService reloaded = serviceWithStorage(storage);
assertEquals("NON_COMPLIANT", reloaded.complianceForRule(REGION, "bucket-policy").complianceType());
assertEquals(1, reloaded.getComplianceDetailsByConfigRule(REGION, "bucket-policy",
null, null, null).items().size());
}
@Test
void deleteConfigRuleCascadesEvaluationsAcrossRestart() {
SharedStorageFactory storage = new SharedStorageFactory();
AwsConfigService first = serviceWithStorage(storage);
first.putConfigRule(REGION, rule("kept-rule", "CUSTOM_LAMBDA",
"arn:aws:lambda:us-east-1:000000000000:function:check"));
first.putConfigRule(REGION, rule("dropped-rule", "CUSTOM_LAMBDA",
"arn:aws:lambda:us-east-1:000000000000:function:check"));
first.putEvaluations(REGION, "kept-rule",
List.of(evaluation("AWS::S3::Bucket", "bucket-1", "COMPLIANT")), false);
first.putEvaluations(REGION, "dropped-rule",
List.of(evaluation("AWS::S3::Bucket", "bucket-1", "NON_COMPLIANT")), false);
first.deleteConfigRule(REGION, "dropped-rule");
AwsConfigService reloaded = serviceWithStorage(storage);
assertEquals("COMPLIANT", reloaded.complianceForRule(REGION, "kept-rule").complianceType());
assertEquals("INSUFFICIENT_DATA", reloaded.complianceForRule(REGION, "dropped-rule").complianceType());
}
@Test
void retentionConfigurationSurvivesRestart() {
SharedStorageFactory storage = new SharedStorageFactory();
AwsConfigService first = serviceWithStorage(storage);
first.putRetentionConfiguration(REGION, 90);
AwsConfigService reloaded = serviceWithStorage(storage);
assertEquals(90, reloaded.describeRetentionConfigurations(REGION, null)
.getFirst().retentionPeriodInDays());
}
private static ConfigRule rule(String name, String owner, String sourceIdentifier) {
return new ConfigRule(name, null, null, null, null,
new ConfigRuleSource(owner, sourceIdentifier, null, null), null, null, null, null, null);
}
private static ConfigEvaluation evaluation(String resourceType, String resourceId, String complianceType) {
return new ConfigEvaluation(resourceType, resourceId, complianceType, null, 1700000000.0, null, null);
}
private static AwsConfigService serviceWithStorage(StorageFactory storage) {
AwsConfigService service = new AwsConfigService(new RegionResolver(REGION, "000000000000"), storage);
service.initializeStorage();
@@ -0,0 +1,580 @@
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 ComplianceEvaluationIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String TARGET_PREFIX = "StarlingDoveService.";
private static final String LAMBDA_RULE = "compliance-loop-rule";
private static final String EXTERNAL_RULE = "external-eval-rule";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static void putRule(String ruleName) {
given()
.header("X-Amz-Target", TARGET_PREFIX + "PutConfigRule")
.contentType(CONTENT_TYPE)
.body("""
{
"ConfigRule": {
"ConfigRuleName": "%s",
"Source": {
"Owner": "CUSTOM_LAMBDA",
"SourceIdentifier": "arn:aws:lambda:us-east-1:000000000000:function:checker"
}
}
}
""".formatted(ruleName))
.when()
.post("/")
.then()
.statusCode(200);
}
@Test
@Order(1)
void setupRules() {
putRule(LAMBDA_RULE);
putRule(EXTERNAL_RULE);
}
@Test
@Order(2)
void putEvaluationsTestModePersistsNothing() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "PutEvaluations")
.contentType(CONTENT_TYPE)
.body("""
{
"ResultToken": "%s",
"TestMode": true,
"Evaluations": [
{
"ComplianceResourceType": "AWS::S3::Bucket",
"ComplianceResourceId": "bucket-1",
"ComplianceType": "NON_COMPLIANT",
"OrderingTimestamp": 1699999999.5
}
]
}
""".formatted(LAMBDA_RULE))
.when()
.post("/")
.then()
.statusCode(200)
.body("FailedEvaluations", hasSize(0));
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeComplianceByConfigRule")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigRuleNames": ["%s"]}
""".formatted(LAMBDA_RULE))
.when()
.post("/")
.then()
.statusCode(200)
.body("ComplianceByConfigRules[0].Compliance.ComplianceType", equalTo("INSUFFICIENT_DATA"));
}
@Test
@Order(3)
void putEvaluationsRecordsCompliance() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "PutEvaluations")
.contentType(CONTENT_TYPE)
.body("""
{
"ResultToken": "%s",
"Evaluations": [
{
"ComplianceResourceType": "AWS::S3::Bucket",
"ComplianceResourceId": "bucket-1",
"ComplianceType": "NON_COMPLIANT",
"Annotation": "Bucket allows public ACLs",
"OrderingTimestamp": 1699999999.5
},
{
"ComplianceResourceType": "AWS::S3::Bucket",
"ComplianceResourceId": "bucket-2",
"ComplianceType": "COMPLIANT",
"OrderingTimestamp": 1699999999.5
}
]
}
""".formatted(LAMBDA_RULE))
.when()
.post("/")
.then()
.statusCode(200)
.body("FailedEvaluations", hasSize(0));
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeComplianceByConfigRule")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigRuleNames": ["%s"]}
""".formatted(LAMBDA_RULE))
.when()
.post("/")
.then()
.statusCode(200)
.body("ComplianceByConfigRules[0].Compliance.ComplianceType", equalTo("NON_COMPLIANT"))
.body("ComplianceByConfigRules[0].Compliance.ComplianceContributorCount.CappedCount", equalTo(1))
.body("ComplianceByConfigRules[0].Compliance.ComplianceContributorCount.CapExceeded", equalTo(false));
}
@Test
@Order(4)
void getComplianceDetailsByConfigRule() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "GetComplianceDetailsByConfigRule")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigRuleName": "%s"}
""".formatted(LAMBDA_RULE))
.when()
.post("/")
.then()
.statusCode(200)
.body("EvaluationResults", hasSize(2))
.body("EvaluationResults[0].EvaluationResultIdentifier.EvaluationResultQualifier.ConfigRuleName",
equalTo(LAMBDA_RULE))
.body("EvaluationResults[0].EvaluationResultIdentifier.EvaluationResultQualifier.ResourceType",
equalTo("AWS::S3::Bucket"))
.body("EvaluationResults[0].EvaluationResultIdentifier.EvaluationResultQualifier.ResourceId",
equalTo("bucket-1"))
.body("EvaluationResults[0].EvaluationResultIdentifier.EvaluationResultQualifier.EvaluationMode",
equalTo("DETECTIVE"))
.body("EvaluationResults[0].EvaluationResultIdentifier.OrderingTimestamp", notNullValue())
.body("EvaluationResults[0].ComplianceType", equalTo("NON_COMPLIANT"))
.body("EvaluationResults[0].Annotation", equalTo("Bucket allows public ACLs"))
.body("EvaluationResults[0].ResultRecordedTime", notNullValue())
.body("EvaluationResults[0].ConfigRuleInvokedTime", notNullValue())
.body("EvaluationResults[1].EvaluationResultIdentifier.EvaluationResultQualifier.ResourceId",
equalTo("bucket-2"))
.body("EvaluationResults[1].ComplianceType", equalTo("COMPLIANT"));
}
@Test
@Order(5)
void getComplianceDetailsFilteredByComplianceType() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "GetComplianceDetailsByConfigRule")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigRuleName": "%s", "ComplianceTypes": ["NON_COMPLIANT"]}
""".formatted(LAMBDA_RULE))
.when()
.post("/")
.then()
.statusCode(200)
.body("EvaluationResults", hasSize(1))
.body("EvaluationResults[0].EvaluationResultIdentifier.EvaluationResultQualifier.ResourceId",
equalTo("bucket-1"));
}
@Test
@Order(6)
void reEvaluationFlipsRuleToCompliant() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "PutEvaluations")
.contentType(CONTENT_TYPE)
.body("""
{
"ResultToken": "%s:on-demand-1",
"Evaluations": [
{
"ComplianceResourceType": "AWS::S3::Bucket",
"ComplianceResourceId": "bucket-1",
"ComplianceType": "COMPLIANT",
"OrderingTimestamp": 1700000100.0
}
]
}
""".formatted(LAMBDA_RULE))
.when()
.post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeComplianceByConfigRule")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigRuleNames": ["%s"]}
""".formatted(LAMBDA_RULE))
.when()
.post("/")
.then()
.statusCode(200)
.body("ComplianceByConfigRules[0].Compliance.ComplianceType", equalTo("COMPLIANT"))
.body("ComplianceByConfigRules[0].Compliance.ComplianceContributorCount", nullValue());
}
@Test
@Order(7)
void allNotApplicableIsInsufficientData() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "PutEvaluations")
.contentType(CONTENT_TYPE)
.body("""
{
"ResultToken": "%s",
"Evaluations": [
{
"ComplianceResourceType": "AWS::S3::Bucket",
"ComplianceResourceId": "bucket-1",
"ComplianceType": "NOT_APPLICABLE",
"OrderingTimestamp": 1700000200.0
},
{
"ComplianceResourceType": "AWS::S3::Bucket",
"ComplianceResourceId": "bucket-2",
"ComplianceType": "NOT_APPLICABLE",
"OrderingTimestamp": 1700000200.0
}
]
}
""".formatted(LAMBDA_RULE))
.when()
.post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeComplianceByConfigRule")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigRuleNames": ["%s"]}
""".formatted(LAMBDA_RULE))
.when()
.post("/")
.then()
.statusCode(200)
.body("ComplianceByConfigRules[0].Compliance.ComplianceType", equalTo("INSUFFICIENT_DATA"));
}
@Test
@Order(8)
void putExternalEvaluation() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "PutExternalEvaluation")
.contentType(CONTENT_TYPE)
.body("""
{
"ConfigRuleName": "%s",
"ExternalEvaluation": {
"ComplianceResourceType": "AWS::EC2::VPC",
"ComplianceResourceId": "vpc-1",
"ComplianceType": "NON_COMPLIANT",
"Annotation": "Flow logs disabled",
"OrderingTimestamp": 1700000300.0
}
}
""".formatted(EXTERNAL_RULE))
.when()
.post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeComplianceByConfigRule")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigRuleNames": ["%s"]}
""".formatted(EXTERNAL_RULE))
.when()
.post("/")
.then()
.statusCode(200)
.body("ComplianceByConfigRules[0].Compliance.ComplianceType", equalTo("NON_COMPLIANT"));
}
@Test
@Order(9)
void describeComplianceByResource() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeComplianceByResource")
.contentType(CONTENT_TYPE)
.body("""
{"ResourceType": "AWS::EC2::VPC"}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("ComplianceByResources", hasSize(1))
.body("ComplianceByResources[0].ResourceType", equalTo("AWS::EC2::VPC"))
.body("ComplianceByResources[0].ResourceId", equalTo("vpc-1"))
.body("ComplianceByResources[0].Compliance.ComplianceType", equalTo("NON_COMPLIANT"))
.body("ComplianceByResources[0].Compliance.ComplianceContributorCount.CappedCount", equalTo(1));
}
@Test
@Order(10)
void getComplianceDetailsByResource() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "GetComplianceDetailsByResource")
.contentType(CONTENT_TYPE)
.body("""
{"ResourceType": "AWS::EC2::VPC", "ResourceId": "vpc-1"}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("EvaluationResults", hasSize(1))
.body("EvaluationResults[0].EvaluationResultIdentifier.EvaluationResultQualifier.ConfigRuleName",
equalTo(EXTERNAL_RULE))
.body("EvaluationResults[0].Annotation", equalTo("Flow logs disabled"));
}
@Test
@Order(11)
void complianceSummaries() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "GetComplianceSummaryByConfigRule")
.contentType(CONTENT_TYPE)
.body("{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("ComplianceSummary.NonCompliantResourceCount.CappedCount", greaterThanOrEqualTo(1))
.body("ComplianceSummary.ComplianceSummaryTimestamp", notNullValue());
given()
.header("X-Amz-Target", TARGET_PREFIX + "GetComplianceSummaryByResourceType")
.contentType(CONTENT_TYPE)
.body("""
{"ResourceTypes": ["AWS::EC2::VPC"]}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("ComplianceSummariesByResourceType", hasSize(1))
.body("ComplianceSummariesByResourceType[0].ResourceType", equalTo("AWS::EC2::VPC"))
.body("ComplianceSummariesByResourceType[0].ComplianceSummary.NonCompliantResourceCount.CappedCount",
equalTo(1));
}
@Test
@Order(12)
void deleteEvaluationResultsResetsCompliance() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DeleteEvaluationResults")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigRuleName": "%s"}
""".formatted(EXTERNAL_RULE))
.when()
.post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeComplianceByConfigRule")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigRuleNames": ["%s"]}
""".formatted(EXTERNAL_RULE))
.when()
.post("/")
.then()
.statusCode(200)
.body("ComplianceByConfigRules[0].Compliance.ComplianceType", equalTo("INSUFFICIENT_DATA"));
}
@Test
@Order(13)
void putEvaluationsWithoutTokenIsRejected() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "PutEvaluations")
.contentType(CONTENT_TYPE)
.body("""
{
"Evaluations": [
{
"ComplianceResourceType": "AWS::S3::Bucket",
"ComplianceResourceId": "bucket-1",
"ComplianceType": "COMPLIANT",
"OrderingTimestamp": 1700000400.0
}
]
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidResultTokenException"));
}
@Test
@Order(14)
void putEvaluationsForUnknownRuleIsRejected() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "PutEvaluations")
.contentType(CONTENT_TYPE)
.body("""
{
"ResultToken": "no-such-rule",
"Evaluations": [
{
"ComplianceResourceType": "AWS::S3::Bucket",
"ComplianceResourceId": "bucket-1",
"ComplianceType": "COMPLIANT",
"OrderingTimestamp": 1700000400.0
}
]
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("NoSuchConfigRuleException"));
}
@Test
@Order(15)
void putEvaluationsWithInvalidComplianceTypeIsRejected() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "PutEvaluations")
.contentType(CONTENT_TYPE)
.body("""
{
"ResultToken": "%s",
"Evaluations": [
{
"ComplianceResourceType": "AWS::S3::Bucket",
"ComplianceResourceId": "bucket-1",
"ComplianceType": "SORT_OF_COMPLIANT",
"OrderingTimestamp": 1700000400.0
}
]
}
""".formatted(LAMBDA_RULE))
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
}
@Test
@Order(16)
void putExternalEvaluationForUnknownRuleIsRejected() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "PutExternalEvaluation")
.contentType(CONTENT_TYPE)
.body("""
{
"ConfigRuleName": "no-such-rule",
"ExternalEvaluation": {
"ComplianceResourceType": "AWS::EC2::VPC",
"ComplianceResourceId": "vpc-1",
"ComplianceType": "COMPLIANT",
"OrderingTimestamp": 1700000500.0
}
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("NoSuchConfigRuleException"));
}
@Test
@Order(17)
void staleEvaluationDoesNotOverwriteNewerResult() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "PutEvaluations")
.contentType(CONTENT_TYPE)
.body("""
{
"ResultToken": "%s:stale",
"Evaluations": [
{
"ComplianceResourceType": "AWS::S3::Bucket",
"ComplianceResourceId": "bucket-1",
"ComplianceType": "COMPLIANT",
"OrderingTimestamp": 1700000150.0
}
]
}
""".formatted(LAMBDA_RULE))
.when()
.post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", TARGET_PREFIX + "GetComplianceDetailsByConfigRule")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigRuleName": "%s"}
""".formatted(LAMBDA_RULE))
.when()
.post("/")
.then()
.statusCode(200)
.body("EvaluationResults.find { it.EvaluationResultIdentifier.EvaluationResultQualifier.ResourceId == 'bucket-1' }.ComplianceType",
equalTo("NOT_APPLICABLE"))
.body("EvaluationResults.find { it.EvaluationResultIdentifier.EvaluationResultQualifier.ResourceId == 'bucket-1' }.EvaluationResultIdentifier.OrderingTimestamp",
equalTo(1700000200.0f));
}
@Test
@Order(18)
void evaluationStatusReflectsRecordedEvaluations() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRuleEvaluationStatus")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigRuleNames": ["%s"]}
""".formatted(LAMBDA_RULE))
.when()
.post("/")
.then()
.statusCode(200)
.body("ConfigRulesEvaluationStatus[0].FirstEvaluationStarted", equalTo(true))
.body("ConfigRulesEvaluationStatus[0].LastSuccessfulInvocationTime", notNullValue())
.body("ConfigRulesEvaluationStatus[0].LastSuccessfulEvaluationTime", notNullValue());
}
@Test
@Order(19)
void cleanupRules() {
for (String ruleName : new String[]{LAMBDA_RULE, EXTERNAL_RULE}) {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DeleteConfigRule")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigRuleName": "%s"}
""".formatted(ruleName))
.when()
.post("/")
.then()
.statusCode(200);
}
}
}
@@ -0,0 +1,230 @@
package io.github.hectorvent.floci.services.configservice;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.json.JsonPath;
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 java.util.ArrayList;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ConfigPaginationIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String TARGET_PREFIX = "StarlingDoveService.";
private static final int SEEDED_RULES = 30;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static String seededRuleName(int index) {
return "pg-rule-%03d".formatted(index);
}
@Test
@Order(1)
void seedRules() {
for (int i = 0; i < SEEDED_RULES; i++) {
given()
.header("X-Amz-Target", TARGET_PREFIX + "PutConfigRule")
.contentType(CONTENT_TYPE)
.body("""
{
"ConfigRule": {
"ConfigRuleName": "%s",
"Source": {
"Owner": "CUSTOM_LAMBDA",
"SourceIdentifier": "arn:aws:lambda:us-east-1:000000000000:function:checker"
}
}
}
""".formatted(seededRuleName(i)))
.when()
.post("/")
.then()
.statusCode(200);
}
}
@Test
@Order(2)
void describeConfigRulesReturnsPageOf25WithNextToken() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRules")
.contentType(CONTENT_TYPE)
.body("{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("ConfigRules", hasSize(25))
.body("NextToken", notNullValue());
}
@Test
@Order(3)
void nextTokenWalkCollectsAllSeededRules() {
List<String> collected = new ArrayList<>();
String nextToken = null;
do {
String body = nextToken == null ? "{}" : "{\"NextToken\": \"%s\"}".formatted(nextToken);
JsonPath response = given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRules")
.contentType(CONTENT_TYPE)
.body(body)
.when()
.post("/")
.then()
.statusCode(200)
.extract().jsonPath();
collected.addAll(response.getList("ConfigRules.ConfigRuleName", String.class));
nextToken = response.getString("NextToken");
} while (nextToken != null);
for (int i = 0; i < SEEDED_RULES; i++) {
String name = seededRuleName(i);
assertTrue(collected.contains(name), "walk must return seeded rule " + name);
}
}
@Test
@Order(4)
void invalidNextTokenIsRejected() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRules")
.contentType(CONTENT_TYPE)
.body("""
{"NextToken": "not-a-token"}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidNextTokenException"));
}
@Test
@Order(5)
void complianceDetailsHonorLimitAndNextToken() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "PutEvaluations")
.contentType(CONTENT_TYPE)
.body("""
{
"ResultToken": "%s",
"Evaluations": [
{
"ComplianceResourceType": "AWS::Lambda::Function",
"ComplianceResourceId": "fn-1",
"ComplianceType": "COMPLIANT",
"OrderingTimestamp": 1700000000.0
},
{
"ComplianceResourceType": "AWS::Lambda::Function",
"ComplianceResourceId": "fn-2",
"ComplianceType": "COMPLIANT",
"OrderingTimestamp": 1700000000.0
},
{
"ComplianceResourceType": "AWS::Lambda::Function",
"ComplianceResourceId": "fn-3",
"ComplianceType": "NON_COMPLIANT",
"OrderingTimestamp": 1700000000.0
}
]
}
""".formatted(seededRuleName(0)))
.when()
.post("/")
.then()
.statusCode(200);
String nextToken = given()
.header("X-Amz-Target", TARGET_PREFIX + "GetComplianceDetailsByConfigRule")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigRuleName": "%s", "Limit": 2}
""".formatted(seededRuleName(0)))
.when()
.post("/")
.then()
.statusCode(200)
.body("EvaluationResults", hasSize(2))
.body("NextToken", notNullValue())
.extract().jsonPath().getString("NextToken");
given()
.header("X-Amz-Target", TARGET_PREFIX + "GetComplianceDetailsByConfigRule")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigRuleName": "%s", "Limit": 2, "NextToken": "%s"}
""".formatted(seededRuleName(0), nextToken))
.when()
.post("/")
.then()
.statusCode(200)
.body("EvaluationResults", hasSize(1))
.body("NextToken", nullValue());
}
@Test
@Order(6)
void complianceDetailsLimitAbove100IsRejected() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "GetComplianceDetailsByConfigRule")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigRuleName": "%s", "Limit": 101}
""".formatted(seededRuleName(0)))
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
}
@Test
@Order(7)
void conformancePackLimitAbove20IsRejected() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeConformancePacks")
.contentType(CONTENT_TYPE)
.body("""
{"Limit": 21}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidLimitException"));
}
@Test
@Order(8)
void cleanupSeededRules() {
for (int i = 0; i < SEEDED_RULES; i++) {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DeleteConfigRule")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigRuleName": "%s"}
""".formatted(seededRuleName(i)))
.when()
.post("/")
.then()
.statusCode(200);
}
}
}
@@ -33,10 +33,23 @@ class ConfigRuleIntegrationTest {
{
"ConfigRule": {
"ConfigRuleName": "rule-crud-test",
"Description": "Ensure S3 access points block public access",
"Scope": {
"ComplianceResourceTypes": ["AWS::S3::AccessPoint"],
"TagKey": "env"
},
"Source": {
"Owner": "AWS",
"SourceIdentifier": "S3_ACCESS_POINT_PUBLIC_ACCESS_BLOCKS"
}
"SourceIdentifier": "S3_ACCESS_POINT_PUBLIC_ACCESS_BLOCKS",
"SourceDetails": [
{
"EventSource": "aws.config",
"MessageType": "ScheduledNotification"
}
]
},
"InputParameters": "{\\"mode\\":\\"strict\\"}",
"MaximumExecutionFrequency": "TwentyFour_Hours"
}
}
""")
@@ -64,8 +77,16 @@ class ConfigRuleIntegrationTest {
.body("ConfigRules[0].ConfigRuleArn", notNullValue())
.body("ConfigRules[0].ConfigRuleId", notNullValue())
.body("ConfigRules[0].ConfigRuleState", equalTo("ACTIVE"))
.body("ConfigRules[0].Description", equalTo("Ensure S3 access points block public access"))
.body("ConfigRules[0].Scope.ComplianceResourceTypes", contains("AWS::S3::AccessPoint"))
.body("ConfigRules[0].Scope.TagKey", equalTo("env"))
.body("ConfigRules[0].Source.Owner", equalTo("AWS"))
.body("ConfigRules[0].Source.SourceIdentifier", equalTo("S3_ACCESS_POINT_PUBLIC_ACCESS_BLOCKS"));
.body("ConfigRules[0].Source.SourceIdentifier", equalTo("S3_ACCESS_POINT_PUBLIC_ACCESS_BLOCKS"))
.body("ConfigRules[0].Source.SourceDetails[0].EventSource", equalTo("aws.config"))
.body("ConfigRules[0].Source.SourceDetails[0].MessageType", equalTo("ScheduledNotification"))
.body("ConfigRules[0].InputParameters", equalTo("{\"mode\":\"strict\"}"))
.body("ConfigRules[0].MaximumExecutionFrequency", equalTo("TwentyFour_Hours"))
.body("ConfigRules[0].EvaluationModes[0].Mode", equalTo("DETECTIVE"));
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRules")
@@ -80,6 +101,22 @@ class ConfigRuleIntegrationTest {
@Test
@Order(3)
void describeConfigRulesUnknownName() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRules")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigRuleNames": ["no-such-rule"]}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("NoSuchConfigRuleException"));
}
@Test
@Order(4)
void describeComplianceByConfigRule() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeComplianceByConfigRule")
@@ -97,7 +134,7 @@ class ConfigRuleIntegrationTest {
}
@Test
@Order(4)
@Order(5)
void putConfigRuleUpdate() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "PutConfigRule")
@@ -128,12 +165,14 @@ class ConfigRuleIntegrationTest {
.post("/")
.then()
.statusCode(200)
.body("ConfigRules[0].Source.Owner", equalTo("CUSTOM_LAMBDA"));
.body("ConfigRules[0].Source.Owner", equalTo("CUSTOM_LAMBDA"))
.body("ConfigRules[0].ConfigRuleArn", notNullValue())
.body("ConfigRules[0].ConfigRuleId", notNullValue());
}
@Test
@Order(5)
void describeConfigRuleEvaluationStatus() {
@Order(6)
void describeConfigRuleEvaluationStatusBeforeStart() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRuleEvaluationStatus")
.contentType(CONTENT_TYPE)
@@ -148,11 +187,13 @@ class ConfigRuleIntegrationTest {
.body("ConfigRulesEvaluationStatus[0].ConfigRuleName", equalTo("rule-crud-test"))
.body("ConfigRulesEvaluationStatus[0].ConfigRuleArn", notNullValue())
.body("ConfigRulesEvaluationStatus[0].ConfigRuleId", notNullValue())
.body("ConfigRulesEvaluationStatus[0].FirstEvaluationStarted", equalTo(true));
.body("ConfigRulesEvaluationStatus[0].FirstEvaluationStarted", equalTo(false))
.body("ConfigRulesEvaluationStatus[0].FirstActivatedTime", notNullValue())
.body("ConfigRulesEvaluationStatus[0].LastSuccessfulInvocationTime", nullValue());
}
@Test
@Order(6)
@Order(7)
void startConfigRulesEvaluation() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "StartConfigRulesEvaluation")
@@ -164,10 +205,23 @@ class ConfigRuleIntegrationTest {
.post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRuleEvaluationStatus")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigRuleNames": ["rule-crud-test"]}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("ConfigRulesEvaluationStatus[0].FirstEvaluationStarted", equalTo(true))
.body("ConfigRulesEvaluationStatus[0].LastSuccessfulInvocationTime", notNullValue());
}
@Test
@Order(7)
@Order(8)
void startConfigRulesEvaluationNonexistent() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "StartConfigRulesEvaluation")
@@ -183,7 +237,7 @@ class ConfigRuleIntegrationTest {
}
@Test
@Order(8)
@Order(9)
void deleteConfigRule() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DeleteConfigRule")
@@ -198,7 +252,7 @@ class ConfigRuleIntegrationTest {
}
@Test
@Order(9)
@Order(10)
void deleteNonexistentConfigRule() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DeleteConfigRule")
@@ -212,4 +266,175 @@ class ConfigRuleIntegrationTest {
.statusCode(400)
.body("__type", equalTo("NoSuchConfigRuleException"));
}
@Test
@Order(11)
void deleteConfigRuleWithoutNameIsRejected() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DeleteConfigRule")
.contentType(CONTENT_TYPE)
.body("""
{}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("NoSuchConfigRuleException"));
}
/**
* PutConfigRule now deserializes the whole modeled ConfigRule and stores it, so every
* enum-typed member it keeps has to be checked: {@code Source/Owner},
* {@code MaximumExecutionFrequency}, {@code ConfigRuleState} and
* {@code EvaluationModes[].Mode}. A rule stored with a value outside its enum is echoed
* straight back by DescribeConfigRules as a rule AWS would never have accepted.
*/
@Test
@Order(11)
void putConfigRuleRejectsValuesOutsideTheModeledEnums() {
record Case(String name, String body) { }
Case[] cases = {
new Case("Owner", """
{"ConfigRule": {"ConfigRuleName": "rule-enum-owner",
"Source": {"Owner": "CUSTOM", "SourceIdentifier": "X"}}}"""),
new Case("MaximumExecutionFrequency", """
{"ConfigRule": {"ConfigRuleName": "rule-enum-freq",
"Source": {"Owner": "AWS", "SourceIdentifier": "X"},
"MaximumExecutionFrequency": "Two_Hours"}}"""),
new Case("ConfigRuleState", """
{"ConfigRule": {"ConfigRuleName": "rule-enum-state",
"Source": {"Owner": "AWS", "SourceIdentifier": "X"},
"ConfigRuleState": "PAUSED"}}"""),
new Case("EvaluationMode", """
{"ConfigRule": {"ConfigRuleName": "rule-enum-mode",
"Source": {"Owner": "AWS", "SourceIdentifier": "X"},
"EvaluationModes": [{"Mode": "REACTIVE"}]}}"""),
};
for (Case c : cases) {
given()
.header("X-Amz-Target", TARGET_PREFIX + "PutConfigRule")
.contentType(CONTENT_TYPE)
.body(c.body())
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
}
// Nothing was stored under any of the rejected names.
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRules")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigRuleNames": ["rule-enum-owner"]}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("NoSuchConfigRuleException"));
}
/**
* The nested members are stored and echoed back too: {@code SourceDetails[]} carries the
* EventSource ({@code aws.config} only), MessageType and MaximumExecutionFrequency enums,
* and {@code Scope.ComplianceResourceTypes} is a list with {@code max: 100}.
*/
@Test
@Order(11)
void putConfigRuleRejectsNestedValuesOutsideTheModeledShapes() {
String[] bodies = {
"""
{"ConfigRule": {"ConfigRuleName": "rule-enum-eventsource",
"Source": {"Owner": "AWS", "SourceIdentifier": "X",
"SourceDetails": [{"EventSource": "aws.cloudtrail", "MessageType": "ScheduledNotification"}]}}}""",
"""
{"ConfigRule": {"ConfigRuleName": "rule-enum-messagetype",
"Source": {"Owner": "AWS", "SourceIdentifier": "X",
"SourceDetails": [{"EventSource": "aws.config", "MessageType": "PeriodicNotification"}]}}}""",
"""
{"ConfigRule": {"ConfigRuleName": "rule-enum-detail-freq",
"Source": {"Owner": "AWS", "SourceIdentifier": "X",
"SourceDetails": [{"EventSource": "aws.config", "MessageType": "ScheduledNotification",
"MaximumExecutionFrequency": "Two_Hours"}]}}}""",
};
for (String body : bodies) {
given()
.header("X-Amz-Target", TARGET_PREFIX + "PutConfigRule")
.contentType(CONTENT_TYPE)
.body(body)
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
}
StringBuilder tooManyTypes = new StringBuilder();
for (int i = 0; i < 101; i++) {
tooManyTypes.append(i == 0 ? "" : ", ").append("\"AWS::S3::Bucket").append(i).append('"');
}
given()
.header("X-Amz-Target", TARGET_PREFIX + "PutConfigRule")
.contentType(CONTENT_TYPE)
.body("{\"ConfigRule\": {\"ConfigRuleName\": \"rule-scope-cardinality\","
+ " \"Source\": {\"Owner\": \"AWS\", \"SourceIdentifier\": \"X\"},"
+ " \"Scope\": {\"ComplianceResourceTypes\": [" + tooManyTypes + "]}}}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRules")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigRuleNames": ["rule-enum-eventsource"]}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("NoSuchConfigRuleException"));
}
/**
* {@code ComplianceTypes} is a list of the ComplianceType enum with {@code max: 3}. It is
* read as a filter, so an unmodeled value silently narrows the result to nothing — the
* caller reads that as "no rules match" rather than as the rejection AWS sends.
*/
@Test
@Order(12)
void describeComplianceByConfigRuleRejectsAnUnmodeledComplianceTypeFilter() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeComplianceByConfigRule")
.contentType(CONTENT_TYPE)
.body("""
{"ComplianceTypes": ["PARTIALLY_COMPLIANT"]}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
}
@Test
@Order(12)
void describeComplianceByConfigRuleRejectsMoreThanThreeComplianceTypes() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeComplianceByConfigRule")
.contentType(CONTENT_TYPE)
.body("""
{"ComplianceTypes": ["COMPLIANT", "NON_COMPLIANT", "NOT_APPLICABLE", "INSUFFICIENT_DATA"]}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
}
}
@@ -216,4 +216,120 @@ class ConfigurationRecorderIntegrationTest {
.statusCode(200)
.body("DeliveryChannels", hasSize(1));
}
// --- Deletes ---
@Test
@Order(10)
void deleteDeliveryChannelWhileRecorderRunning() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "StartConfigurationRecorder")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigurationRecorderName": "default"}
""")
.when()
.post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", TARGET_PREFIX + "DeleteDeliveryChannel")
.contentType(CONTENT_TYPE)
.body("""
{"DeliveryChannelName": "default"}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("LastDeliveryChannelDeleteFailedException"));
}
@Test
@Order(11)
void deleteDeliveryChannelAfterRecorderStopped() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "StopConfigurationRecorder")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigurationRecorderName": "default"}
""")
.when()
.post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", TARGET_PREFIX + "DeleteDeliveryChannel")
.contentType(CONTENT_TYPE)
.body("""
{"DeliveryChannelName": "default"}
""")
.when()
.post("/")
.then()
.statusCode(200);
}
@Test
@Order(12)
void deleteDeliveryChannelAgain() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DeleteDeliveryChannel")
.contentType(CONTENT_TYPE)
.body("""
{"DeliveryChannelName": "default"}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("NoSuchDeliveryChannelException"));
}
@Test
@Order(13)
void deleteConfigurationRecorder() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DeleteConfigurationRecorder")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigurationRecorderName": "default"}
""")
.when()
.post("/")
.then()
.statusCode(200);
}
@Test
@Order(14)
void describeConfigurationRecordersAfterDelete() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigurationRecorders")
.contentType(CONTENT_TYPE)
.body("{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("ConfigurationRecorders", hasSize(0));
}
@Test
@Order(15)
void deleteConfigurationRecorderAgain() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DeleteConfigurationRecorder")
.contentType(CONTENT_TYPE)
.body("""
{"ConfigurationRecorderName": "default"}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("NoSuchConfigurationRecorderException"));
}
}
@@ -0,0 +1,35 @@
package io.github.hectorvent.floci.services.configservice;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* DescribeConfigRules' ConfigRuleNames member is modeled with {@code Maximum 25 items}
* (confirmed against botocore's config service-2.json). Every other array-size limit this
* PR touches (Scope.ComplianceResourceTypes, PutEvaluations, PutRetentionConfiguration's
* day range) is enforced; this one was not.
*/
class DescribeConfigRulesLimitTest {
private static final String REGION = "us-east-1";
@Test
void rejectsMoreThanTwentyFiveRuleNames() {
AwsConfigService service = new AwsConfigService(new RegionResolver(REGION, "000000000000"), null);
List<String> tooMany = new ArrayList<>();
for (int i = 0; i < 26; i++) {
tooMany.add("rule-" + i);
}
AwsException ex = assertThrows(AwsException.class,
() -> service.describeConfigRules(REGION, tooMany));
assertEquals("InvalidParameterValueException", ex.getErrorCode());
}
}
@@ -0,0 +1,131 @@
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 RetentionConfigurationIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String TARGET_PREFIX = "StarlingDoveService.";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
@Order(1)
void putRetentionConfiguration() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "PutRetentionConfiguration")
.contentType(CONTENT_TYPE)
.body("""
{"RetentionPeriodInDays": 365}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("RetentionConfiguration.Name", equalTo("default"))
.body("RetentionConfiguration.RetentionPeriodInDays", equalTo(365));
}
@Test
@Order(2)
void describeRetentionConfigurations() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeRetentionConfigurations")
.contentType(CONTENT_TYPE)
.body("{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("RetentionConfigurations", hasSize(1))
.body("RetentionConfigurations[0].Name", equalTo("default"))
.body("RetentionConfigurations[0].RetentionPeriodInDays", equalTo(365));
}
@Test
@Order(3)
void putRetentionConfigurationBelowMinimumIsRejected() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "PutRetentionConfiguration")
.contentType(CONTENT_TYPE)
.body("""
{"RetentionPeriodInDays": 29}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
}
@Test
@Order(4)
void describeRetentionConfigurationsUnknownName() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeRetentionConfigurations")
.contentType(CONTENT_TYPE)
.body("""
{"RetentionConfigurationNames": ["no-such-retention"]}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("NoSuchRetentionConfigurationException"));
}
@Test
@Order(5)
void deleteRetentionConfiguration() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DeleteRetentionConfiguration")
.contentType(CONTENT_TYPE)
.body("""
{"RetentionConfigurationName": "default"}
""")
.when()
.post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeRetentionConfigurations")
.contentType(CONTENT_TYPE)
.body("{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("RetentionConfigurations", hasSize(0));
}
@Test
@Order(6)
void deleteRetentionConfigurationAgainIsRejected() {
given()
.header("X-Amz-Target", TARGET_PREFIX + "DeleteRetentionConfiguration")
.contentType(CONTENT_TYPE)
.body("""
{"RetentionConfigurationName": "default"}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("NoSuchRetentionConfigurationException"));
}
}