fix(config): check requests against the modeled constraints (#8363)

The Config handler read each member with asText, asInt or path and
checked only some of them by hand, so an empty or over-long Arn on the
two recorder Describe calls answered
NoSuchConfigurationRecorderException, and an empty ResourceArn on the
three tag operations was accepted, as was an over-long one that isn't
a Config resource's ARN.

tools/aws/regen_config_shapes.py now vendors every Config operation's
request constraints from botocore, kept in sync by make aws-data-check,
and RequestConstraintCheck checks each served operation's request
before it runs. A violation is a ValidationException, which the model
documents for missing required fields and input that fails validation,
and a Limit out of range answers the InvalidLimitException its
operation models.

The hand-written checks the table covers are gone, putConfigRule's
included: ConfigCfnProvisioner now checks the rule it builds as a
PutConfigRule request before storing it, so a template property outside
the constraints fails the resource. A rule without a ConfigRuleName
keeps its InvalidParameterValueException, since the model doesn't
require the member.

The loop that drops blob and timestamp members moves into
request_shapes as drop_blob_and_timestamp_members, used by both the
Config and Kinesis generators. Both vendored files are unchanged.
This commit is contained in:
soreavis authored and GitHub committed 2026-11-14 19:35:00 -04:00
1 parent 08b2bae267
commit 6de963848b
21 files changed
+3506 -286

No files matched your search

+5
View File
@@ -302,6 +302,7 @@ aws-data-sync-botocore: ## Regenerate only the AWS data derived from botocore, s
$(PYTHON) tools/aws/regen_securityhub_shapes.py
$(PYTHON) tools/aws/regen_rekognition_shapes.py
$(PYTHON) tools/aws/regen_kinesis_shapes.py
$(PYTHON) tools/aws/regen_config_shapes.py
$(PYTHON) tools/aws/regen_iam_shapes.py
$(PYTHON) tools/aws/regen_sts_shapes.py
$(PYTHON) tools/aws/regen_apigateway_types.py
@@ -439,6 +440,10 @@ aws-data-check-botocore: ## The AWS data derived from botocore must match a fres
echo "error: Kinesis request shapes are out of date; run 'make aws-data-sync'."; \
exit 1; \
}
@$(PYTHON) tools/aws/regen_config_shapes.py --check || { \
echo "error: AWS Config request shapes are out of date; run 'make aws-data-sync'."; \
exit 1; \
}
@$(PYTHON) tools/aws/regen_apigateway_types.py --check || { \
echo "error: API Gateway integration types are out of date; run 'make aws-data-sync'."; \
exit 1; \
+14 -5
View File
@@ -204,12 +204,21 @@ aws configservice delete-config-rule --config-rule-name s3-bucket-versioning
`ResourceNotFoundException` for a config rule, conformance pack, aggregation
authorization or configuration recorder ARN that does not name an existing resource in the
caller's account and region. ARNs of resource kinds Floci does not model (configuration
aggregators, stored queries, organization rules and packs) are accepted without a check.
aggregators, stored queries, organization rules and packs) are accepted without an existence check.
- `PutConfigRule` applies its `Tags` only when it creates the rule; a later
`PutConfigRule` for the same rule leaves its tags unchanged, as AWS documents. Use
`TagResource` and `UntagResource` to change them. `DeleteConfigRule` drops the rule's tags.
`PutConfigurationRecorder` and `DeleteConfigurationRecorder` do the same for the recorder.
- `PutConfigRule` and `PutAggregationAuthorization` reject more than 50 `Tags`, a tag
without a 1-128 character `Key`, or a `Value` over 256 characters with
`InvalidParameterValueException`, and store nothing. `PutConfigurationRecorder` rejects
the same with `ValidationException`. A tag with no `Value` is stored with an empty value.
- Every request is checked by `RequestConstraintCheck` against the types, required
members, bounds, patterns and enums generated from botocore's AWS Config service model.
`tools/aws/regen_config_shapes.py` vendors every operation's input constraints;
`make aws-data-sync` regenerates them and `make aws-data-check` checks for drift. A
violation answers `ValidationException`, or `InvalidLimitException` for a `Limit` out of
range where the operation models that error, in Floci's own wording. CloudFormation
checks an `AWS::Config::ConfigRule` against `PutConfigRule`'s constraints the same way,
so a property outside them fails the resource with that message.
- `PutConfigRule`, `PutAggregationAuthorization` and `PutConfigurationRecorder` reject more
than 50 `Tags`, a `Key` outside 1-128 characters or a `Value` over 256 characters with
`ValidationException`, and a tag without a `Key` with the operation's modelled error
(`InvalidParameterValueException` for the first two). They store nothing. A tag with no
`Value` is stored with an empty value.
@@ -1,9 +1,11 @@
package io.floci.aws.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.configservice.AwsConfigService;
import io.floci.aws.services.configservice.ConfigRequestShapes;
import io.floci.aws.services.configservice.model.ConfigRule;
import io.floci.aws.services.configservice.model.ConfigRuleSource;
import io.floci.aws.services.configservice.model.CustomPolicyDetails;
@@ -22,6 +24,7 @@ import java.util.Set;
public class ConfigCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(ConfigCfnProvisioner.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String CONFIG_RULE = "AWS::Config::ConfigRule";
private final AwsConfigService configService;
@@ -49,11 +52,14 @@ public class ConfigCfnProvisioner implements CfnResourceProvisioner {
? ctx.generatePhysicalName(resource.getLogicalId(), 128, false)
: previousName;
}
ConfigRule rule = configService.putConfigRule(ctx.region(), new ConfigRule(
ConfigRule desired = new ConfigRule(
name, null, null, text(resolved, "Description"), scope(resolved.path("Scope")),
source(resolved.path("Source")), inputParameters(resolved.path("InputParameters")),
text(resolved, "MaximumExecutionFrequency"), null, null,
evaluationModes(resolved.path("EvaluationModes"))));
evaluationModes(resolved.path("EvaluationModes")));
ConfigRequestShapes.check("PutConfigRule",
MAPPER.createObjectNode().set("ConfigRule", MAPPER.valueToTree(desired)));
ConfigRule rule = configService.putConfigRule(ctx.region(), desired);
resource.setPhysicalId(rule.configRuleName());
resource.getAttributes().put("Arn", rule.configRuleArn());
resource.getAttributes().put("ConfigRuleId", rule.configRuleId());
@@ -26,7 +26,6 @@ import io.floci.aws.services.configservice.model.EvaluationResult;
import io.floci.aws.services.configservice.model.EvaluationResultIdentifier;
import io.floci.aws.services.configservice.model.EvaluationResultQualifier;
import io.floci.aws.services.configservice.model.RetentionConfiguration;
import io.floci.aws.services.configservice.model.SourceDetail;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -38,46 +37,20 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@ApplicationScoped
public class AwsConfigService {
private static final Set<String> VALID_COMPLIANCE_TYPES =
Set.of("COMPLIANT", "NON_COMPLIANT", "NOT_APPLICABLE", "INSUFFICIENT_DATA");
private static final String NO_SUCH_CONFIG_RULE_MESSAGE =
"The ConfigRule provided in the request is invalid. Please check the configRule name.";
private static final String INVALID_NEXT_TOKEN_MESSAGE =
"The specified next token is not valid. Specify the nextToken string that was returned "
+ "in the previous response to get the next page of results.";
/** Enum shapes from the Config model (config/2014-11-12/service-2.json). */
private static final Set<String> VALID_RULE_OWNERS =
Set.of("CUSTOM_LAMBDA", "AWS", "CUSTOM_POLICY");
private static final Set<String> VALID_EXECUTION_FREQUENCIES =
Set.of("One_Hour", "Three_Hours", "Six_Hours", "Twelve_Hours", "TwentyFour_Hours");
private static final Set<String> VALID_RULE_STATES =
Set.of("ACTIVE", "DELETING", "DELETING_RESULTS", "EVALUATING");
private static final Set<String> VALID_EVALUATION_MODES = Set.of("DETECTIVE", "PROACTIVE");
private static final Set<String> VALID_EVENT_SOURCES = Set.of("aws.config");
private static final Set<String> VALID_MESSAGE_TYPES = Set.of(
"ConfigurationItemChangeNotification", "ConfigurationSnapshotDeliveryCompleted",
"ScheduledNotification", "OversizedConfigurationItemChangeNotification");
/** {@code ComplianceTypes} is a list of ComplianceType with {@code max: 3}. */
private static final int MAX_COMPLIANCE_TYPE_FILTERS = 3;
/** {@code Scope.ComplianceResourceTypes} is {@code max: 100}. */
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;
@@ -204,44 +177,11 @@ public class AwsConfigService {
* the tags alone, which TagResource/UntagResource change instead. The get-then-put runs under
* the lock delete takes, so a delete cannot land between them and orphan the creation tags. */
public ConfigRule putConfigRule(String region, ConfigRule requested, List<Map<String, String>> tagList) {
if (requested == null || isBlank(requested.configRuleName())) {
String ruleName = requested.configRuleName();
if (ruleName == null) {
throw new AwsException("InvalidParameterValueException",
"ConfigRuleName must be specified.", 400);
}
if (requested.source() == null || isBlank(requested.source().owner())) {
throw new AwsException("InvalidParameterValueException",
"Source with Owner must be specified.", 400);
}
// The whole modeled ConfigRule is stored and echoed back, so every enum-typed member
// it keeps is checked here rather than accepted verbatim.
requireEnum(requested.source().owner(), VALID_RULE_OWNERS, "Source.Owner");
requireEnum(requested.maximumExecutionFrequency(), VALID_EXECUTION_FREQUENCIES,
"MaximumExecutionFrequency");
requireEnum(requested.configRuleState(), VALID_RULE_STATES, "ConfigRuleState");
if (requested.source().sourceDetails() != null) {
for (SourceDetail detail : requested.source().sourceDetails()) {
if (detail == null) {
continue;
}
requireEnum(detail.eventSource(), VALID_EVENT_SOURCES, "SourceDetails.EventSource");
requireEnum(detail.messageType(), VALID_MESSAGE_TYPES, "SourceDetails.MessageType");
requireEnum(detail.maximumExecutionFrequency(), VALID_EXECUTION_FREQUENCIES,
"SourceDetails.MaximumExecutionFrequency");
}
}
if (requested.scope() != null && requested.scope().complianceResourceTypes() != null
&& requested.scope().complianceResourceTypes().size() > MAX_COMPLIANCE_RESOURCE_TYPES) {
throw new AwsException("InvalidParameterValueException",
"Scope.ComplianceResourceTypes accepts at most "
+ MAX_COMPLIANCE_RESOURCE_TYPES + " values.", 400);
}
if (requested.evaluationModes() != null) {
for (EvaluationModeConfiguration mode : requested.evaluationModes()) {
requireEnum(mode == null ? null : mode.mode(), VALID_EVALUATION_MODES,
"EvaluationModes.Mode");
}
}
String ruleName = requested.configRuleName();
synchronized (lockFor(ruleKey(region, ruleName))) {
return storeConfigRule(region, requested, ruleName, tagList);
}
@@ -305,10 +245,6 @@ public class AwsConfigService {
}
public List<ConfigRule> describeConfigRules(String region, List<String> ruleNames) {
if (ruleNames != null && ruleNames.size() > MAX_DESCRIBE_CONFIG_RULE_NAMES) {
throw new AwsException("InvalidParameterValueException",
"ConfigRuleNames accepts at most " + MAX_DESCRIBE_CONFIG_RULE_NAMES + " values.", 400);
}
Map<String, ConfigRule> store = rulesFor(region);
List<ConfigRule> result = new ArrayList<>();
if (ruleNames == null || ruleNames.isEmpty()) {
@@ -327,8 +263,7 @@ public class AwsConfigService {
}
public Paged<ConfigRule> describeConfigRulesPaged(String region, List<String> ruleNames, String nextToken) {
return paginate(describeConfigRules(region, ruleNames), null, nextToken,
25, 25, "InvalidParameterValueException");
return paginate(describeConfigRules(region, ruleNames), null, nextToken, 25);
}
public Paged<ConfigRuleEvaluationStatus> describeConfigRuleEvaluationStatus(String region,
@@ -349,7 +284,7 @@ public class AwsConfigService {
evaluationStarted, ruleFirstActivatedTime.get(key),
lastEvaluationTime, lastEvaluationTime));
}
return paginate(statuses, limit, nextToken, 150, 150, "InvalidParameterValueException");
return paginate(statuses, limit, nextToken, 150);
}
public void startConfigRulesEvaluation(String region, List<String> ruleNames) {
@@ -372,10 +307,6 @@ public class AwsConfigService {
throw new AwsException("InvalidResultTokenException",
"The specified ResultToken is not valid.", 400);
}
if (newEvaluations.size() > 100) {
throw new AwsException("InvalidParameterValueException",
"The Evaluations list cannot contain more than 100 items.", 400);
}
newEvaluations.forEach(this::validateEvaluation);
if (testMode) {
return;
@@ -414,11 +345,6 @@ public class AwsConfigService {
"Each evaluation must specify ComplianceResourceType, ComplianceResourceId, "
+ "ComplianceType and OrderingTimestamp.", 400);
}
if (!VALID_COMPLIANCE_TYPES.contains(evaluation.complianceType())) {
throw new AwsException("InvalidParameterValueException",
"ComplianceType must be one of COMPLIANT, NON_COMPLIANT, NOT_APPLICABLE, "
+ "INSUFFICIENT_DATA.", 400);
}
}
private void storeEvaluations(String region, String ruleName, List<ConfigEvaluation> newEvaluations) {
@@ -470,7 +396,6 @@ public class AwsConfigService {
public Paged<ComplianceByConfigRule> describeComplianceByConfigRule(String region, List<String> ruleNames,
List<String> complianceTypes, String nextToken) {
validateComplianceTypeFilter(complianceTypes);
List<ComplianceByConfigRule> entries = new ArrayList<>();
for (ConfigRule rule : describeConfigRules(region, ruleNames)) {
Compliance compliance = complianceForRule(region, rule.configRuleName());
@@ -478,12 +403,11 @@ public class AwsConfigService {
entries.add(new ComplianceByConfigRule(rule.configRuleName(), compliance));
}
}
return paginate(entries, null, nextToken, 25, 25, "InvalidParameterValueException");
return paginate(entries, null, nextToken, 25);
}
public Paged<ComplianceByResource> describeComplianceByResource(String region, String resourceType,
String resourceId, List<String> complianceTypes, Integer limit, String nextToken) {
validateComplianceTypeFilter(complianceTypes);
if (!isBlank(resourceId) && isBlank(resourceType)) {
throw new AwsException("InvalidParameterValueException",
"ResourceType must be specified when ResourceId is provided.", 400);
@@ -500,12 +424,11 @@ public class AwsConfigService {
}
entries.sort(Comparator.comparing(ComplianceByResource::resourceType)
.thenComparing(ComplianceByResource::resourceId));
return paginate(entries, limit, nextToken, 10, 100, "InvalidParameterValueException");
return paginate(entries, limit, nextToken, 10);
}
public Paged<EvaluationResult> getComplianceDetailsByConfigRule(String region, String ruleName,
List<String> complianceTypes, Integer limit, String nextToken) {
validateComplianceTypeFilter(complianceTypes);
requireRule(region, ruleName);
List<EvaluationResult> results = evaluationsFor(region)
.getOrDefault(ruleName, Map.of()).values().stream()
@@ -514,12 +437,11 @@ public class AwsConfigService {
.thenComparing(ConfigEvaluation::complianceResourceId))
.map(e -> toEvaluationResult(ruleName, e))
.collect(Collectors.toList());
return paginate(results, limit, nextToken, 10, 100, "InvalidParameterValueException");
return paginate(results, limit, nextToken, 10);
}
public Paged<EvaluationResult> getComplianceDetailsByResource(String region, String resourceType,
String resourceId, List<String> complianceTypes, String nextToken) {
validateComplianceTypeFilter(complianceTypes);
if (isBlank(resourceType) || isBlank(resourceId)) {
throw new AwsException("InvalidParameterValueException",
"ResourceType and ResourceId must be specified.", 400);
@@ -534,7 +456,7 @@ public class AwsConfigService {
});
results.sort(Comparator.comparing(r ->
r.evaluationResultIdentifier().evaluationResultQualifier().configRuleName()));
return paginate(results, null, nextToken, 10, 10, "InvalidParameterValueException");
return paginate(results, null, nextToken, 10);
}
public ComplianceSummary getComplianceSummaryByConfigRule(String region) {
@@ -554,10 +476,6 @@ public class AwsConfigService {
public List<ComplianceSummaryByResourceType> getComplianceSummaryByResourceType(String region,
List<String> resourceTypes) {
if (resourceTypes != null && resourceTypes.size() > 20) {
throw new AwsException("InvalidParameterValueException",
"ResourceTypes cannot contain more than 20 items.", 400);
}
Map<String, long[]> countsByType = new HashMap<>();
for (List<ConfigEvaluation> resourceEvaluations
: groupEvaluationsByResource(region, null, null).values()) {
@@ -640,36 +558,6 @@ public class AwsConfigService {
return complianceTypes == null || complianceTypes.isEmpty() || complianceTypes.contains(complianceType);
}
/**
* A {@code ComplianceTypes} filter outside the modeled enum (or longer than the list's
* {@code max: 3}) would otherwise match nothing and read to the caller as "no results"
* instead of the rejection AWS answers.
*/
private static void validateComplianceTypeFilter(List<String> complianceTypes) {
if (complianceTypes == null || complianceTypes.isEmpty()) {
return;
}
if (complianceTypes.size() > MAX_COMPLIANCE_TYPE_FILTERS) {
throw new AwsException("InvalidParameterValueException",
"ComplianceTypes accepts at most " + MAX_COMPLIANCE_TYPE_FILTERS + " values.", 400);
}
for (String complianceType : complianceTypes) {
requireEnum(complianceType, VALID_COMPLIANCE_TYPES, "ComplianceTypes");
}
}
/** Rejects a non-blank value that is not a member of the shape's enum; a null/blank value is left alone. */
private static void requireEnum(String value, Set<String> allowed, String memberName) {
if (isBlank(value) || allowed.contains(value)) {
return;
}
throw new AwsException("InvalidParameterValueException",
"Value '" + value + "' at '" + memberName + "' failed to satisfy constraint: "
+ "Member must satisfy enum value set: ["
+ allowed.stream().sorted().collect(Collectors.joining(", ")) + "]",
400);
}
private ComplianceContributorCount contributorCount(long count, int cap) {
return new ComplianceContributorCount((int) Math.min(count, cap), count > cap);
}
@@ -866,10 +754,6 @@ public class AwsConfigService {
// --- Retention Configuration ---
public RetentionConfiguration putRetentionConfiguration(String region, Integer retentionPeriodInDays) {
if (retentionPeriodInDays == null || retentionPeriodInDays < 30 || retentionPeriodInDays > 2557) {
throw new AwsException("InvalidParameterValueException",
"RetentionPeriodInDays must be between 30 and 2557.", 400);
}
RetentionConfiguration configuration = new RetentionConfiguration("default", retentionPeriodInDays);
retentionConfigurations.put(region, configuration);
return configuration;
@@ -889,10 +773,6 @@ public class AwsConfigService {
}
public void deleteRetentionConfiguration(String region, String name) {
if (isBlank(name)) {
throw new AwsException("InvalidParameterValueException",
"RetentionConfigurationName must be specified.", 400);
}
RetentionConfiguration configuration = retentionConfigurations.get(region);
if (configuration == null || !configuration.name().equals(name)) {
throw new AwsException("NoSuchRetentionConfigurationException",
@@ -967,8 +847,7 @@ public class AwsConfigService {
public Paged<ConformancePack> describeConformancePacksPaged(String region, List<String> names,
Integer limit, String nextToken) {
return paginate(describeConformancePacks(region, names), limit, nextToken,
20, 20, "InvalidLimitException");
return paginate(describeConformancePacks(region, names), limit, nextToken, 20);
}
public Paged<ConformancePackStatusDetail> describeConformancePackStatus(String region, List<String> names,
@@ -982,7 +861,7 @@ public class AwsConfigService {
"CREATE_SUCCESSFUL",
now()));
}
return paginate(result, limit, nextToken, 20, 20, "InvalidLimitException");
return paginate(result, limit, nextToken, 20);
}
// --- Aggregation Authorizations ---
@@ -997,7 +876,7 @@ public class AwsConfigService {
* 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);
requireAuthorizedAwsRegion(authorizedAwsRegion);
synchronized (lockFor(authorizationLockKey(region, authorizedAccountId, authorizedAwsRegion))) {
Map<String, AggregationAuthorization> store = authorizationsFor(region);
String key = authorizationKey(authorizedAccountId, authorizedAwsRegion);
@@ -1024,8 +903,7 @@ public class AwsConfigService {
.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");
return paginate(result, limit, nextToken, 100);
}
/** The Config model declares no "not found" error for this operation, so deleting an
@@ -1038,7 +916,7 @@ public class AwsConfigService {
* authorization already gone. */
public void deleteAggregationAuthorization(String region, String authorizedAccountId,
String authorizedAwsRegion) {
requireAuthorizationKey(authorizedAccountId, authorizedAwsRegion);
requireAuthorizedAwsRegion(authorizedAwsRegion);
synchronized (lockFor(authorizationLockKey(region, authorizedAccountId, authorizedAwsRegion))) {
Map<String, AggregationAuthorization> store = authorizationsFor(region);
AggregationAuthorization removed =
@@ -1056,11 +934,7 @@ public class AwsConfigService {
"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);
}
private static void requireAuthorizedAwsRegion(String authorizedAwsRegion) {
if (isBlank(authorizedAwsRegion)) {
throw new AwsException("InvalidParameterValueException",
"AuthorizedAwsRegion must be specified.", 400);
@@ -1177,17 +1051,9 @@ public class AwsConfigService {
public record Paged<T>(List<T> items, String nextToken) {}
/** Offset-as-NextToken pagination over a pre-sorted list. A null or zero limit falls back to
* the default page size; limits outside [1, maxLimit] fail with the op-specific error code. */
private <T> Paged<T> paginate(List<T> items, Integer limit, String nextToken,
int defaultPageSize, int maxLimit, String limitErrorCode) {
int pageSize = defaultPageSize;
if (limit != null && limit != 0) {
if (limit < 0 || limit > maxLimit) {
throw new AwsException(limitErrorCode,
"Limit must be between 0 and " + maxLimit + ".", 400);
}
pageSize = limit;
}
* the default page size; ConfigRequestShapes has already checked the limit's modeled range. */
private <T> Paged<T> paginate(List<T> items, Integer limit, String nextToken, int defaultPageSize) {
int pageSize = limit == null || limit == 0 ? defaultPageSize : limit;
int offset = 0;
if (nextToken != null && !nextToken.isEmpty()) {
try {
@@ -0,0 +1,63 @@
package io.floci.aws.services.configservice;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RequestConstraintCheck;
import java.util.List;
import java.util.Set;
/**
* Checks AWS Config requests against the constraints generated by {@code tools/aws/regen_config_shapes.py}.
* A violation is a {@code ValidationException}, which the model documents for missing required fields and
* input that fails validation. A {@code Limit} out of range answers {@code InvalidLimitException} instead
* where the operation models it.
*/
public final class ConfigRequestShapes {
private static final Set<String> MODELED_LIMITS = Set.of(
"DescribeAggregationAuthorizations.Limit", "DescribeConformancePacks.Limit",
"DescribeConformancePackStatus.Limit", "ListTagsForResource.Limit");
private static final RequestConstraintCheck.Messages VALIDATION =
RequestConstraintCheck.standardMessages("ValidationException");
private static final RequestConstraintCheck.Messages INVALID_LIMIT =
RequestConstraintCheck.standardMessages("InvalidLimitException");
private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load(
"aws/config-request-shapes.json", "AWS Config request shapes",
new RequestConstraintCheck.Messages() {
@Override
public AwsException type(String path, String type) {
return VALIDATION.type(path, type);
}
@Override
public AwsException bounds(String path, String type, Long min, Long max, Number size) {
return (MODELED_LIMITS.contains(path) ? INVALID_LIMIT : VALIDATION).bounds(path, type, min, max, size);
}
@Override
public AwsException pattern(String path, String pattern) {
return VALIDATION.pattern(path, pattern);
}
@Override
public AwsException enumValue(String path, List<String> values) {
return VALIDATION.enumValue(path, values);
}
@Override
public AwsException required(String path) {
return VALIDATION.required(path);
}
});
private ConfigRequestShapes() {
}
public static void check(String operation, JsonNode request) {
if (CHECK.hasOperation(operation)) {
CHECK.check(operation, request);
}
}
}
@@ -25,6 +25,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
@ApplicationScoped
public class ConfigServiceJsonHandler {
@@ -39,46 +40,48 @@ public class ConfigServiceJsonHandler {
}
public Response handle(String action, JsonNode request, String region) throws Exception {
return switch (action) {
case "PutConfigRule" -> putConfigRule(request, region);
case "DeleteConfigRule" -> deleteConfigRule(request, region);
case "DescribeConfigRules" -> describeConfigRules(request, region);
case "DescribeComplianceByConfigRule" -> describeComplianceByConfigRule(request, region);
case "DescribeComplianceByResource" -> describeComplianceByResource(request, region);
case "DescribeConfigRuleEvaluationStatus" -> describeConfigRuleEvaluationStatus(request, region);
case "StartConfigRulesEvaluation" -> startConfigRulesEvaluation(request, region);
case "PutEvaluations" -> putEvaluations(request, region);
case "PutExternalEvaluation" -> putExternalEvaluation(request, region);
case "DeleteEvaluationResults" -> deleteEvaluationResults(request, region);
case "GetComplianceDetailsByConfigRule" -> getComplianceDetailsByConfigRule(request, region);
case "GetComplianceDetailsByResource" -> getComplianceDetailsByResource(request, region);
case "GetComplianceSummaryByConfigRule" -> getComplianceSummaryByConfigRule(region);
case "GetComplianceSummaryByResourceType" -> getComplianceSummaryByResourceType(request, region);
case "PutConformancePack" -> putConformancePack(request, region);
case "DeleteConformancePack" -> deleteConformancePack(request, region);
case "DescribeConformancePacks" -> describeConformancePacks(request, region);
case "DescribeConformancePackStatus" -> describeConformancePackStatus(request, region);
case "PutConfigurationRecorder" -> putConfigurationRecorder(request, region);
case "DescribeConfigurationRecorders" -> describeConfigurationRecorders(request, region);
case "DeleteConfigurationRecorder" -> deleteConfigurationRecorder(request, region);
case "StartConfigurationRecorder" -> startConfigurationRecorder(request, region);
case "StopConfigurationRecorder" -> stopConfigurationRecorder(request, region);
case "DescribeConfigurationRecorderStatus" -> describeConfigurationRecorderStatus(request, region);
case "PutDeliveryChannel" -> putDeliveryChannel(request, region);
case "DescribeDeliveryChannels" -> describeDeliveryChannels(request, region);
case "DeleteDeliveryChannel" -> deleteDeliveryChannel(request, region);
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, region);
case "UntagResource" -> untagResource(request, region);
case "ListTagsForResource" -> listTagsForResource(request, region);
Callable<Response> operation = switch (action) {
case "PutConfigRule" -> () -> putConfigRule(request, region);
case "DeleteConfigRule" -> () -> deleteConfigRule(request, region);
case "DescribeConfigRules" -> () -> describeConfigRules(request, region);
case "DescribeComplianceByConfigRule" -> () -> describeComplianceByConfigRule(request, region);
case "DescribeComplianceByResource" -> () -> describeComplianceByResource(request, region);
case "DescribeConfigRuleEvaluationStatus" -> () -> describeConfigRuleEvaluationStatus(request, region);
case "StartConfigRulesEvaluation" -> () -> startConfigRulesEvaluation(request, region);
case "PutEvaluations" -> () -> putEvaluations(request, region);
case "PutExternalEvaluation" -> () -> putExternalEvaluation(request, region);
case "DeleteEvaluationResults" -> () -> deleteEvaluationResults(request, region);
case "GetComplianceDetailsByConfigRule" -> () -> getComplianceDetailsByConfigRule(request, region);
case "GetComplianceDetailsByResource" -> () -> getComplianceDetailsByResource(request, region);
case "GetComplianceSummaryByConfigRule" -> () -> getComplianceSummaryByConfigRule(region);
case "GetComplianceSummaryByResourceType" -> () -> getComplianceSummaryByResourceType(request, region);
case "PutConformancePack" -> () -> putConformancePack(request, region);
case "DeleteConformancePack" -> () -> deleteConformancePack(request, region);
case "DescribeConformancePacks" -> () -> describeConformancePacks(request, region);
case "DescribeConformancePackStatus" -> () -> describeConformancePackStatus(request, region);
case "PutConfigurationRecorder" -> () -> putConfigurationRecorder(request, region);
case "DescribeConfigurationRecorders" -> () -> describeConfigurationRecorders(request, region);
case "DeleteConfigurationRecorder" -> () -> deleteConfigurationRecorder(request, region);
case "StartConfigurationRecorder" -> () -> startConfigurationRecorder(request, region);
case "StopConfigurationRecorder" -> () -> stopConfigurationRecorder(request, region);
case "DescribeConfigurationRecorderStatus" -> () -> describeConfigurationRecorderStatus(request, region);
case "PutDeliveryChannel" -> () -> putDeliveryChannel(request, region);
case "DescribeDeliveryChannels" -> () -> describeDeliveryChannels(request, region);
case "DeleteDeliveryChannel" -> () -> deleteDeliveryChannel(request, region);
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, region);
case "UntagResource" -> () -> untagResource(request, region);
case "ListTagsForResource" -> () -> listTagsForResource(request, region);
default -> throw new AwsException(
"InvalidAction", "Could not find operation " + action, 400);
};
ConfigRequestShapes.check(action, request);
return operation.call();
}
// --- Config Rules ---
@@ -371,28 +374,13 @@ public class ConfigServiceJsonHandler {
}
/** PutConfigRule, PutAggregationAuthorization and PutConfigurationRecorder take a
* {@code TagsList} (config/2014-11-12: at most 50 {@code Tag}s, Key 1-128 characters,
* optional Value of at most 256). The first two model {@code InvalidParameterValueException}
* as their only parameter error; PutConfigurationRecorder models {@code ValidationException}.
* Checked before the service stores anything, so a rejected request leaves no resource
* behind. An absent Value is optional in the model and is stored as the empty string. */
* {@code TagsList}, whose count and Key and Value lengths ConfigRequestShapes has checked.
* The model leaves a tag's Key optional, so a tag without one is refused here, with the
* operation's modelled parameter error, before the service stores anything. An absent Value
* is optional in the model and is stored as the empty string. */
private List<Map<String, String>> extractCreationTags(JsonNode req, String errorCode) {
JsonNode tags = req.path("Tags");
if (tags.isMissingNode() || tags.isNull()) {
return List.of();
}
if (!tags.isArray()) {
throw new AwsException(errorCode, "Tags must be a list.", 400);
}
if (tags.size() > 50) {
throw new AwsException(errorCode, "Tags must contain at most 50 tags.", 400);
}
for (JsonNode tag : tags) {
JsonNode key = tag.path("Key");
JsonNode value = tag.path("Value");
boolean valueOk = value.isMissingNode() || value.isNull()
|| (value.isTextual() && value.asText().length() <= 256);
if (!key.isTextual() || key.asText().isEmpty() || key.asText().length() > 128 || !valueOk) {
for (JsonNode tag : req.path("Tags")) {
if (!tag.path("Key").isTextual()) {
throw new AwsException(errorCode,
"Each tag needs a Key of 1-128 characters and a Value of at most 256 characters.", 400);
}
File diff suppressed because it is too large. Load diff
@@ -9,6 +9,8 @@ import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.configservice.AwsConfigService;
import io.floci.aws.services.configservice.model.ConfigRule;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
@@ -124,6 +126,36 @@ class ConfigCfnProvisionerTest {
verifyNoInteractions(config);
}
@ParameterizedTest
@ValueSource(strings = {
"{\"Source\":{}}",
"{\"Source\":{\"Owner\":\"SOMEONE\"}}",
"{\"Source\":{\"Owner\":\"CUSTOM_LAMBDA\",\"SourceDetails\":[{\"MessageType\":\"Daily\"}]}}",
"{\"Source\":{\"Owner\":\"AWS\"},\"MaximumExecutionFrequency\":\"Hourly\"}",
"{\"Source\":{\"Owner\":\"AWS\"},\"EvaluationModes\":[{\"Mode\":\"BOTH\"}]}"})
void configRuleOutsideTheModeledConstraintsFailsBeforeCallingConfig(String props) throws Exception {
JsonNode template = mapper.readTree(props);
AwsException failure = assertThrows(AwsException.class,
() -> provisioner.provision(resource(), template, context()));
assertEquals("ValidationException", failure.getErrorCode());
verifyNoInteractions(config);
}
@Test
void configRuleViolationUsesTheConfigValidationMessage() {
ObjectNode props = mapper.createObjectNode().put("Description", "d".repeat(257));
props.set("Source", mapper.createObjectNode().put("Owner", "AWS"));
AwsException failure = assertThrows(AwsException.class,
() -> provisioner.provision(resource(), props, context()));
assertEquals("Invalid parameter at 'ConfigRule.Description' failed to satisfy constraint: "
+ "'Member must have length less than or equal to 256'", failure.getMessage());
verifyNoInteractions(config);
}
@Test
void scopeWithoutComplianceResourceTypesLeavesThemUnset() {
ObjectNode props = mapper.createObjectNode().put("ConfigRuleName", "tagged-only");
@@ -182,11 +182,23 @@ class AggregationAuthorizationIntegrationTest {
""")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
.body("__type", equalTo("ValidationException"));
}
/** DescribeAggregationAuthorizations models InvalidLimitException for a Limit out of range. */
@Test
@Order(9)
void describeRejectsALimitAboveTheModeledMaximum() {
RestAssuredJsonUtils.awsAction("StarlingDoveService", "DescribeAggregationAuthorizations", """
{"Limit": 101}
""")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidLimitException"));
}
@Test
@Order(9)
@Order(10)
void unrelatedActionsStillReportInvalidAction() {
call("PutAggregationAuthorizations", authorizationBody())
.then()
@@ -245,15 +245,6 @@ class AwsConfigServiceAggregationAuthorizationTest {
assertTrue(service.storedTags(arn).isEmpty(), "the deleted pack's tags survived");
}
@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();
@@ -263,15 +254,6 @@ class AwsConfigServiceAggregationAuthorizationTest {
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();
@@ -424,7 +424,7 @@ class ComplianceEvaluationIntegrationTest {
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidResultTokenException"));
.body("__type", equalTo("ValidationException"));
}
@Test
@@ -476,7 +476,7 @@ class ComplianceEvaluationIntegrationTest {
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
.body("__type", equalTo("ValidationException"));
}
@Test
@@ -192,7 +192,7 @@ class ConfigPaginationIntegrationTest {
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
.body("__type", equalTo("ValidationException"));
}
@Test
@@ -10,7 +10,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@@ -284,7 +284,7 @@ class ConfigRuleIntegrationTest {
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("NoSuchConfigRuleException"));
.body("__type", equalTo("ValidationException"));
}
/**
@@ -324,7 +324,7 @@ class ConfigRuleIntegrationTest {
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
.body("__type", equalTo("ValidationException"));
}
// Nothing was stored under any of the rejected names.
@@ -373,7 +373,7 @@ class ConfigRuleIntegrationTest {
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
.body("__type", equalTo("ValidationException"));
}
StringBuilder tooManyTypes = new StringBuilder();
@@ -390,7 +390,7 @@ class ConfigRuleIntegrationTest {
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
.body("__type", equalTo("ValidationException"));
given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRules")
@@ -423,7 +423,7 @@ class ConfigRuleIntegrationTest {
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
.body("__type", equalTo("ValidationException"));
}
@Test
@@ -439,7 +439,7 @@ class ConfigRuleIntegrationTest {
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
.body("__type", equalTo("ValidationException"));
}
@Test
@@ -478,19 +478,20 @@ class ConfigRuleIntegrationTest {
}
/** PutConfigRule's TagsList (config/2014-11-12): at most 50 tags, Key 1-128, Value 0-256,
* rejected with the operation's modelled InvalidParameterValueException and nothing stored. */
* rejected with ValidationException and nothing stored. The model leaves Key optional, so a
* tag without one keeps the operation's modelled InvalidParameterValueException. */
@Test
@Order(101)
void putConfigRuleRejectsInvalidTagsWithoutCreatingTheRule() {
String fiftyOne = String.join(",", Collections.nCopies(51, "{\"Key\": \"k\", \"Value\": \"v\"}"));
List<String> invalid = List.of(
"{\"Value\": \"v\"}",
"{\"Key\": \"\", \"Value\": \"v\"}",
"{\"Key\": \"" + "k".repeat(129) + "\", \"Value\": \"v\"}",
"{\"Key\": \"k\", \"Value\": \"" + "v".repeat(257) + "\"}",
"{\"Key\": 7, \"Value\": \"v\"}",
fiftyOne);
for (String tags : invalid) {
Map<String, String> invalid = Map.of(
"{\"Value\": \"v\"}", "InvalidParameterValueException",
"{\"Key\": \"\", \"Value\": \"v\"}", "ValidationException",
"{\"Key\": \"" + "k".repeat(129) + "\", \"Value\": \"v\"}", "ValidationException",
"{\"Key\": \"k\", \"Value\": \"" + "v".repeat(257) + "\"}", "ValidationException",
"{\"Key\": 7, \"Value\": \"v\"}", "ValidationException",
fiftyOne, "ValidationException");
invalid.forEach((tags, errorCode) ->
post("PutConfigRule", """
{
"ConfigRule": {
@@ -501,8 +502,7 @@ class ConfigRuleIntegrationTest {
}
""".formatted(tags))
.then().statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
}
.body("__type", equalTo(errorCode)));
post("DescribeConfigRules", "{\"ConfigRuleNames\": [\"rule-bad-tags\"]}")
.then().statusCode(400)
.body("__type", equalTo("NoSuchConfigRuleException"));
@@ -531,7 +531,7 @@ class ConfigRuleIntegrationTest {
post("DeleteConfigRule", "{\"ConfigRuleName\": \"rule-keyonly-tag\"}").then().statusCode(200);
}
/** PutAggregationAuthorization takes the same TagsList and models the same error. */
/** PutAggregationAuthorization takes the same TagsList. */
@Test
@Order(103)
void putAggregationAuthorizationRejectsAnInvalidTag() {
@@ -540,7 +540,7 @@ class ConfigRuleIntegrationTest {
"Tags": [{"Key": "", "Value": "v"}]}
""")
.then().statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
.body("__type", equalTo("ValidationException"));
post("DescribeAggregationAuthorizations", "{}")
.then().statusCode(200)
.body("AggregationAuthorizations.AuthorizedAccountId", not(hasItem("444455556666")));
@@ -8,6 +8,8 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@@ -146,6 +148,53 @@ class ConfigTaggingIntegrationTest {
.body("__type", equalTo("ResourceNotFoundException"));
}
/** ResourceArn is an AmazonResourceName, 1-1000 characters, on all three tag operations. */
@Test
@Order(6)
void aResourceArnOutsideItsModeledLengthIsAValidationException() {
Map<String, String> requests = Map.of(
"TagResource", "{\"ResourceArn\": \"%s\", \"Tags\": [{\"Key\": \"k\", \"Value\": \"v\"}]}",
"UntagResource", "{\"ResourceArn\": \"%s\", \"TagKeys\": [\"k\"]}",
"ListTagsForResource", "{\"ResourceArn\": \"%s\"}");
requests.forEach((action, body) -> {
RestAssuredJsonUtils.awsAction("StarlingDoveService", action, body.formatted(""))
.then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("Invalid parameter at 'ResourceArn' failed to satisfy constraint: "
+ "'Member must have length greater than or equal to 1'"));
RestAssuredJsonUtils.awsAction("StarlingDoveService", action, body.formatted("a".repeat(1001)))
.then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("Invalid parameter at 'ResourceArn' failed to satisfy constraint: "
+ "'Member must have length less than or equal to 1000'"));
});
}
/** A missing required member and a member of the wrong JSON type fail before the operation runs;
* ListTagsForResource models InvalidLimitException for a Limit out of range. */
@Test
@Order(7)
void requestsOutsideTheModeledShapesFailBeforeTheOperationRuns() {
String arn = getConfigRuleArn("tag-test-rule");
RestAssuredJsonUtils.awsAction("StarlingDoveService", "UntagResource", """
{"ResourceArn": "%s"}
""".formatted(arn))
.then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("Invalid parameter at 'TagKeys' failed to satisfy constraint: "
+ "'Member must not be null'"));
RestAssuredJsonUtils.awsAction("StarlingDoveService", "TagResource", """
{"ResourceArn": "%s", "Tags": {"Key": "k", "Value": "v"}}
""".formatted(arn))
.then().statusCode(400)
.body("__type", equalTo("ValidationException"));
RestAssuredJsonUtils.awsAction("StarlingDoveService", "ListTagsForResource", """
{"ResourceArn": "%s", "Limit": 101}
""".formatted(arn))
.then().statusCode(400)
.body("__type", equalTo("InvalidLimitException"));
}
private String getConfigRuleArn(String ruleName) {
return given()
.header("X-Amz-Target", TARGET_PREFIX + "DescribeConfigRules")
@@ -8,6 +8,8 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@@ -432,8 +434,7 @@ class ConfigurationRecorderIntegrationTest {
.body("ConfigurationRecorders[0]", not(hasKey("recordingMode")));
}
/** PutConfigurationRecorder's Tags is a TagsList, and the operation models ValidationException,
* not the InvalidParameterValueException PutConfigRule answers. */
/** PutConfigurationRecorder's Tags is a TagsList, and the operation models ValidationException. */
@Test
@Order(19)
void putConfigurationRecorderRejectsAnInvalidTagWithoutStoringIt() {
@@ -592,4 +593,22 @@ class ConfigurationRecorderIntegrationTest {
.then().statusCode(400)
.body("__type", equalTo("NoSuchConfigurationRecorderException"));
}
/** Arn is an AmazonResourceName, 1-1000 characters, on both Describe calls. */
@Test
@Order(23)
void anArnOutsideItsModeledLengthIsAValidationException() {
for (String action : List.of("DescribeConfigurationRecorders", "DescribeConfigurationRecorderStatus")) {
RestAssuredJsonUtils.awsAction("StarlingDoveService", action, "{\"Arn\": \"\"}")
.then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("Invalid parameter at 'Arn' failed to satisfy constraint: "
+ "'Member must have length greater than or equal to 1'"));
RestAssuredJsonUtils.awsAction("StarlingDoveService", action, "{\"Arn\": \"" + "a".repeat(1001) + "\"}")
.then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("Invalid parameter at 'Arn' failed to satisfy constraint: "
+ "'Member must have length less than or equal to 1000'"));
}
}
}
@@ -1,20 +1,19 @@
package io.floci.aws.services.configservice;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.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.
* (confirmed against botocore's config service-2.json), which ConfigRequestShapes checks
* before the handler reads the names.
*/
class DescribeConfigRulesLimitTest {
@@ -22,14 +21,17 @@ class DescribeConfigRulesLimitTest {
@Test
void rejectsMoreThanTwentyFiveRuleNames() {
AwsConfigService service = new AwsConfigService(new RegionResolver(REGION, "000000000000"), null);
List<String> tooMany = new ArrayList<>();
ObjectMapper mapper = new ObjectMapper();
ConfigServiceJsonHandler handler = new ConfigServiceJsonHandler(
new AwsConfigService(new RegionResolver(REGION, "000000000000"), null), mapper);
ObjectNode request = mapper.createObjectNode();
ArrayNode tooMany = request.putArray("ConfigRuleNames");
for (int i = 0; i < 26; i++) {
tooMany.add("rule-" + i);
}
AwsException ex = assertThrows(AwsException.class,
() -> service.describeConfigRules(REGION, tooMany));
assertEquals("InvalidParameterValueException", ex.getErrorCode());
() -> handler.handle("DescribeConfigRules", request, REGION));
assertEquals("ValidationException", ex.getErrorCode());
}
}
@@ -69,7 +69,7 @@ class RetentionConfigurationIntegrationTest {
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterValueException"));
.body("__type", equalTo("ValidationException"));
}
@Test
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env python3
"""Vendor every AWS Config operation's request constraints for RequestConstraintCheck."""
from __future__ import annotations
from pathlib import Path
import request_shapes
MODEL = Path("config/2014-11-12")
OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/config-request-shapes.json"
def main(argv: list[str] | None = None) -> int:
return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT,
description=__doc__, constraints=True,
prepare=request_shapes.drop_blob_and_timestamp_members)
if __name__ == "__main__":
raise SystemExit(main())
+2 -14
View File
@@ -10,22 +10,10 @@ MODEL = Path("kinesis/2013-12-02")
OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/kinesis-request-shapes.json"
def prepare(model: dict) -> dict:
# The shared checker does not parse blob or timestamp wire types. Keep their required
# markers while leaving present values to the existing handlers (including PutRecords'
# per-record error path for malformed Data).
for shape in model["shapes"].values():
if shape["type"] != "structure":
continue
for member, spec in list(shape.get("members", {}).items()):
if model["shapes"][spec["shape"]]["type"] in {"blob", "timestamp"}:
del shape["members"][member]
return model
def main(argv: list[str] | None = None) -> int:
return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT,
description=__doc__, constraints=True, prepare=prepare)
description=__doc__, constraints=True,
prepare=request_shapes.drop_blob_and_timestamp_members)
if __name__ == "__main__":
+15
View File
@@ -141,6 +141,21 @@ def widen_partition_and_region(model: dict) -> dict:
return model
def drop_blob_and_timestamp_members(model: dict) -> dict:
"""The model, with every structure member whose shape is a blob or a timestamp dropped.
`RequestConstraintCheck` parses neither wire type, so a present value is left to the service's
handler. The structure still lists a dropped member as required, so a request without it is refused.
"""
for shape in model["shapes"].values():
if shape["type"] != "structure":
continue
for member, spec in list(shape.get("members", {}).items()):
if model["shapes"][spec["shape"]]["type"] in {"blob", "timestamp"}:
del shape["members"][member]
return model
def render(doc: dict) -> str:
return json.dumps(doc, indent=2, sort_keys=False) + "\n"
+15
View File
@@ -30,6 +30,7 @@ import regen_eks_shapes
import regen_emr_serverless_shapes
import regen_iam_shapes
import regen_cloudfront_keyvaluestore_shapes
import regen_config_shapes
import regen_kinesis_shapes
import regen_lambda_microvm_shapes
import regen_organizations_shapes
@@ -269,6 +270,7 @@ CONSTRAINED_MODEL = {
@pytest.mark.parametrize("script, model_path", [
(regen_athena_shapes, "athena/2017-05-18"),
(regen_config_shapes, "config/2014-11-12"),
(regen_kinesis_shapes, "kinesis/2013-12-02"),
(regen_rekognition_shapes, "rekognition/2016-06-27"),
])
@@ -449,6 +451,7 @@ def vendored(script) -> tuple[str, ...]:
regen_resource_groups_shapes, regen_sts_shapes,
regen_securityhub_shapes,
regen_kinesis_shapes,
regen_config_shapes,
regen_rekognition_shapes,
regen_athena_shapes,
regen_cur_shapes,
@@ -569,6 +572,18 @@ def test_kinesis_shapes_keep_tag_bounds_and_leave_wire_types_to_handlers():
assert "Timestamp" not in shapes["GetShardIteratorInput"]["members"]
def test_config_shapes_keep_arn_bounds_and_leave_timestamps_to_handlers():
doc = json.loads(regen_config_shapes.OUTPUT.read_text(encoding="utf-8"))
shapes = doc["shapes"]
assert shapes["DescribeConfigurationRecordersRequest"]["members"]["Arn"] == "AmazonResourceName"
assert shapes["ListTagsForResourceRequest"]["members"]["ResourceArn"] == "AmazonResourceName"
assert shapes["AmazonResourceName"]["min"] == 1
assert shapes["AmazonResourceName"]["max"] == 1000
assert "OrderingTimestamp" not in shapes["Evaluation"]["members"]
assert "OrderingTimestamp" in shapes["Evaluation"]["required"]
def test_securityhub_shapes_keep_required_findings_and_resource_strings():
doc = json.loads(regen_securityhub_shapes.OUTPUT.read_text(encoding="utf-8"))
shapes = doc["shapes"]