mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(cloudformation): generate the create-only table from the registry and compare nested pointers (#8093)
This commit is contained in:
1 parent
b2fa9b3f6c
commit
410e09bf62
11 files changed
+854
-39
No files matched your search
@@ -1,6 +1,7 @@
|
||||
name: CloudFormation Schema Drift
|
||||
# Checks the vendored CloudFormation property types, and the schema surface CfnSchemaCoverageTest
|
||||
# reads, against the resource schemas AWS publishes.
|
||||
# Checks the vendored CloudFormation property types, the schema surface CfnSchemaCoverageTest
|
||||
# reads, and the create-only properties CfnCreateOnlyProperties reads, against the resource schemas
|
||||
# AWS publishes.
|
||||
# They come from AWS's live schema archive rather than from a pinned dependency, so, as with the
|
||||
# IAM data in iam-data-drift.yml, this check can fail without anything in the repository having
|
||||
# changed, and it runs on its own, never as part of a job that ordinary changes trigger.
|
||||
@@ -23,6 +24,10 @@ on:
|
||||
- 'src/test/resources/cloudformation/schema-surface.tsv'
|
||||
- 'tools/aws/regen_cfn_schema_surface.py'
|
||||
- 'tools/aws/test_regen_cfn_schema_surface.py'
|
||||
- 'src/main/resources/cloudformation/create-only-properties.json'
|
||||
- 'src/test/resources/cloudformation/supported-resource-types.tsv'
|
||||
- 'tools/aws/regen_cfn_create_only.py'
|
||||
- 'tools/aws/test_regen_cfn_create_only.py'
|
||||
- '.github/workflows/cfn-schema-drift.yml'
|
||||
schedule:
|
||||
# Mondays at 06:10 UTC, beside the IAM data drift check.
|
||||
@@ -38,7 +43,7 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
cfn-schema-drift:
|
||||
name: Vendored CloudFormation property types and schema surface still match AWS
|
||||
name: Vendored CloudFormation property types, schema surface and create-only properties still match AWS
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
@@ -57,3 +62,7 @@ jobs:
|
||||
- name: Check the committed schema surface still matches AWS's schemas
|
||||
if: always()
|
||||
run: make cfn-schema-surface-verify
|
||||
|
||||
- name: Check the committed create-only properties still match AWS's schemas
|
||||
if: always()
|
||||
run: make cfn-create-only-verify
|
||||
@@ -85,6 +85,7 @@ PREFIX ?= $(HOME)/.local
|
||||
iam-action-resources-test iam-authorized-actions-sync iam-authorized-actions-check \
|
||||
cfn-property-types-sync cfn-property-types-check cfn-property-types-verify cfn-property-types-test \
|
||||
cfn-schema-surface-sync cfn-schema-surface-verify cfn-schema-surface-test \
|
||||
cfn-create-only-sync cfn-create-only-verify cfn-create-only-test \
|
||||
iam-authorized-actions-verify iam-authorized-actions-test iam-passed-roles-sync iam-passed-roles-check \
|
||||
iam-passed-roles-verify iam-passed-roles-test iam-passed-network-connectors-sync \
|
||||
iam-passed-network-connectors-check iam-passed-network-connectors-verify \
|
||||
@@ -813,6 +814,25 @@ cfn-schema-surface-verify: ## CI gate (online): the committed CloudFormation sch
|
||||
cfn-schema-surface-test: ## Run the CloudFormation schema surface generator's unit tests
|
||||
$(PYTHON) -m pytest tools/aws/test_regen_cfn_schema_surface.py -q
|
||||
|
||||
cfn-create-only-sync: ## Regenerate src/main/resources/cloudformation/create-only-properties.json from AWS's resource schemas (commit the result)
|
||||
$(PYTHON) tools/aws/regen_cfn_create_only.py
|
||||
|
||||
cfn-create-only-verify: ## CI gate (online): the committed CloudFormation create-only properties must still match AWS's schemas
|
||||
@$(PYTHON) tools/aws/regen_cfn_create_only.py --verify; status=$$?; \
|
||||
if [ $$status -eq 2 ]; then \
|
||||
echo ""; \
|
||||
echo "error: could not read AWS's CloudFormation resource schemas, so nothing was verified."; \
|
||||
exit 1; \
|
||||
elif [ $$status -ne 0 ]; then \
|
||||
echo ""; \
|
||||
echo "error: AWS has changed a resource schema the CloudFormation create-only properties come from."; \
|
||||
echo " Run 'make cfn-create-only-sync' and commit the result."; \
|
||||
exit 1; \
|
||||
fi
|
||||
|
||||
cfn-create-only-test: ## Run the CloudFormation create-only generator's unit tests
|
||||
$(PYTHON) -m pytest tools/aws/test_regen_cfn_create_only.py -q
|
||||
|
||||
.PHONY: dynamodb-condition-keys-sync dynamodb-condition-keys-check dynamodb-condition-keys-verify
|
||||
dynamodb-condition-keys-sync: ## Regenerate DynamoDB IAM condition keys from AWS and botocore
|
||||
$(PYTHON) tools/aws/regen_dynamodb_condition_keys.py
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
package io.floci.aws.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
@@ -64,4 +67,99 @@ public final class CfnCreateOnlyProperties {
|
||||
public static Set<String> getCreateOnlyProperties(String resourceType) {
|
||||
return PROPERTIES.getOrDefault(resourceType, Collections.emptySet());
|
||||
}
|
||||
|
||||
/** True when the registry table has an entry for the type, so its pointers are authoritative. */
|
||||
public static boolean hasSchema(String resourceType) {
|
||||
return PROPERTIES.containsKey(resourceType);
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the value at any create-only pointer of the type differs between the old and the new
|
||||
* properties. A top-level name compares the whole value (a value added where none existed is not a
|
||||
* change, as before). A nested pointer {@code A/B/C} compares the values at that path: present on
|
||||
* one side only is a change, absent on both is not. A {@code *} segment compares every array
|
||||
* element's subtree.
|
||||
*/
|
||||
public static boolean createOnlyValueChanged(String resourceType, JsonNode oldProps, JsonNode newProps) {
|
||||
for (String pointer : getCreateOnlyProperties(resourceType)) {
|
||||
String[] segments = pointer.split("/");
|
||||
if (pointerChanged(oldProps, newProps, segments, 0, segments.length == 1)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The subtrees of the new properties that sit under a create-only pointer of the type. */
|
||||
public static List<JsonNode> createOnlySubtrees(String resourceType, JsonNode props) {
|
||||
List<JsonNode> out = new ArrayList<>();
|
||||
for (String pointer : getCreateOnlyProperties(resourceType)) {
|
||||
collect(props, pointer.split("/"), 0, out);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static boolean pointerChanged(JsonNode oldNode, JsonNode newNode, String[] segments, int index,
|
||||
boolean topLevel) {
|
||||
if (index == segments.length) {
|
||||
if (topLevel) {
|
||||
return oldNode != null && !oldNode.equals(newNode);
|
||||
}
|
||||
return oldNode == null ? newNode != null : !oldNode.equals(newNode);
|
||||
}
|
||||
if (oldNode == null && newNode == null) {
|
||||
return false;
|
||||
}
|
||||
if (index > 0 && (isIntrinsic(oldNode) || isIntrinsic(newNode))) {
|
||||
// A Ref or Fn:: node stands for a value this walk cannot see into, so compare it whole.
|
||||
return oldNode == null ? newNode != null : !oldNode.equals(newNode);
|
||||
}
|
||||
if ("*".equals(segments[index])) {
|
||||
int size = Math.max(oldNode != null && oldNode.isArray() ? oldNode.size() : 0,
|
||||
newNode != null && newNode.isArray() ? newNode.size() : 0);
|
||||
if (size == 0 && (oldNode != null && !oldNode.isArray() || newNode != null && !newNode.isArray())) {
|
||||
return oldNode == null ? newNode != null : !oldNode.equals(newNode);
|
||||
}
|
||||
for (int i = 0; i < size; i++) {
|
||||
JsonNode o = oldNode != null && oldNode.isArray() ? oldNode.get(i) : null;
|
||||
JsonNode n = newNode != null && newNode.isArray() ? newNode.get(i) : null;
|
||||
if (pointerChanged(o, n, segments, index + 1, false)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
JsonNode o = oldNode != null && oldNode.isObject() ? oldNode.get(segments[index]) : null;
|
||||
JsonNode n = newNode != null && newNode.isObject() ? newNode.get(segments[index]) : null;
|
||||
return pointerChanged(o, n, segments, index + 1, segments.length == 1);
|
||||
}
|
||||
|
||||
private static void collect(JsonNode node, String[] segments, int index, List<JsonNode> out) {
|
||||
if (node == null) {
|
||||
return;
|
||||
}
|
||||
if (index == segments.length || (index > 0 && isIntrinsic(node))) {
|
||||
out.add(node);
|
||||
return;
|
||||
}
|
||||
if ("*".equals(segments[index])) {
|
||||
if (node.isArray()) {
|
||||
for (JsonNode element : node) {
|
||||
collect(element, segments, index + 1, out);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (node.isObject()) {
|
||||
collect(node.get(segments[index]), segments, index + 1, out);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isIntrinsic(JsonNode node) {
|
||||
if (node == null || !node.isObject() || node.size() != 1) {
|
||||
return false;
|
||||
}
|
||||
String key = node.fieldNames().next();
|
||||
return "Ref".equals(key) || key.startsWith("Fn::");
|
||||
}
|
||||
}
|
||||
@@ -1224,16 +1224,27 @@ public class CloudFormationService implements ResourceProvider {
|
||||
boolean createOnlyReferencesReplaced = false;
|
||||
JsonNode props = newDef.path("Properties");
|
||||
if (props != null && props.isObject()) {
|
||||
for (Iterator<String> it = props.fieldNames(); it.hasNext(); ) {
|
||||
String field = it.next();
|
||||
if (CfnCreateOnlyProperties.isCreateOnly(resourceType, field)) {
|
||||
if (CfnCreateOnlyProperties.hasSchema(resourceType)) {
|
||||
for (JsonNode subtree : CfnCreateOnlyProperties.createOnlySubtrees(resourceType, props)) {
|
||||
Set<String> fieldDeps = new LinkedHashSet<>();
|
||||
collectDependencies(props.get(field), allResourceIds, fieldDeps, newConditions);
|
||||
collectDependencies(subtree, allResourceIds, fieldDeps, newConditions);
|
||||
if (fieldDeps.stream().anyMatch(replacedResourceIds::contains)) {
|
||||
createOnlyReferencesReplaced = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (Iterator<String> it = props.fieldNames(); it.hasNext(); ) {
|
||||
String field = it.next();
|
||||
if (CfnCreateOnlyProperties.isCreateOnly(resourceType, field)) {
|
||||
Set<String> fieldDeps = new LinkedHashSet<>();
|
||||
collectDependencies(props.get(field), allResourceIds, fieldDeps, newConditions);
|
||||
if (fieldDeps.stream().anyMatch(replacedResourceIds::contains)) {
|
||||
createOnlyReferencesReplaced = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1303,6 +1314,18 @@ public class CloudFormationService implements ResourceProvider {
|
||||
if (oldProps == null || newProps == null || oldProps.isMissingNode() || newProps.isMissingNode()) {
|
||||
return false;
|
||||
}
|
||||
if (CfnCreateOnlyProperties.hasSchema(resourceType)) {
|
||||
// The registry table names the exact pointers; only a value at one of them replaces.
|
||||
if (CfnCreateOnlyProperties.createOnlyValueChanged(resourceType, oldProps, newProps)) {
|
||||
return true;
|
||||
}
|
||||
for (JsonNode subtree : CfnCreateOnlyProperties.createOnlySubtrees(resourceType, newProps)) {
|
||||
if (referencesAnyParameter(subtree, changedParams) || referencesAnyCondition(subtree, changedConditions)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
for (Iterator<String> it = newProps.fieldNames(); it.hasNext(); ) {
|
||||
String field = it.next();
|
||||
if (CfnCreateOnlyProperties.isCreateOnly(resourceType, field)) {
|
||||
|
||||
@@ -75,9 +75,8 @@
|
||||
],
|
||||
"AWS::AppConfig::Application": [],
|
||||
"AWS::AppConfig::ConfigurationProfile": [
|
||||
"ApplicationId",
|
||||
"LocationUri",
|
||||
"Type"
|
||||
"ApplicationId"
|
||||
],
|
||||
"AWS::AppConfig::DeploymentStrategy": [
|
||||
"Name",
|
||||
@@ -97,14 +96,24 @@
|
||||
"ApiId"
|
||||
],
|
||||
"AWS::AppSync::GraphQLApi": [],
|
||||
"AWS::AppSync::GraphQLSchema": [
|
||||
"ApiId"
|
||||
],
|
||||
"AWS::AppSync::GraphQLSchema": [],
|
||||
"AWS::AppSync::Resolver": [
|
||||
"ApiId",
|
||||
"FieldName",
|
||||
"TypeName"
|
||||
],
|
||||
"AWS::ApplicationAutoScaling::ScalableTarget": [
|
||||
"ResourceId",
|
||||
"ScalableDimension",
|
||||
"ServiceNamespace"
|
||||
],
|
||||
"AWS::ApplicationAutoScaling::ScalingPolicy": [
|
||||
"PolicyName",
|
||||
"ServiceNamespace",
|
||||
"ResourceId",
|
||||
"ScalableDimension",
|
||||
"ScalingTargetId"
|
||||
],
|
||||
"AWS::AutoScaling::AutoScalingGroup": [
|
||||
"InstanceId",
|
||||
"AutoScalingGroupName"
|
||||
@@ -146,7 +155,8 @@
|
||||
"ComputeEnvironmentName",
|
||||
"Tags",
|
||||
"Type",
|
||||
"EksConfiguration",
|
||||
"EksConfiguration/EksClusterArn",
|
||||
"EksConfiguration/KubernetesNamespace",
|
||||
"ComputeResources/ManagedInstancesProvider/InstanceLaunchTemplate/CapacityOptionType",
|
||||
"ComputeResources/ManagedInstancesProvider/InstanceLaunchTemplate/FipsEnabled"
|
||||
],
|
||||
@@ -157,6 +167,17 @@
|
||||
"JobQueueName",
|
||||
"JobQueueType"
|
||||
],
|
||||
"AWS::BedrockAgentCore::Memory": [
|
||||
"Name",
|
||||
"EncryptionKeyArn"
|
||||
],
|
||||
"AWS::BedrockAgentCore::Runtime": [
|
||||
"AgentRuntimeName"
|
||||
],
|
||||
"AWS::BedrockAgentCore::RuntimeEndpoint": [
|
||||
"AgentRuntimeId",
|
||||
"Name"
|
||||
],
|
||||
"AWS::CertificateManager::Certificate": [
|
||||
"SubjectAlternativeNames",
|
||||
"DomainValidationOptions",
|
||||
@@ -188,6 +209,9 @@
|
||||
"AWS::CloudWatch::Alarm": [
|
||||
"AlarmName"
|
||||
],
|
||||
"AWS::CloudWatch::CompositeAlarm": [
|
||||
"AlarmName"
|
||||
],
|
||||
"AWS::CloudWatch::Dashboard": [
|
||||
"DashboardName"
|
||||
],
|
||||
@@ -223,17 +247,33 @@
|
||||
"GroupName"
|
||||
],
|
||||
"AWS::Cognito::UserPoolIdentityProvider": [
|
||||
"UserPoolId",
|
||||
"ProviderName",
|
||||
"ProviderType",
|
||||
"UserPoolId"
|
||||
"ProviderType"
|
||||
],
|
||||
"AWS::Cognito::UserPoolResourceServer": [
|
||||
"Identifier",
|
||||
"UserPoolId"
|
||||
"UserPoolId",
|
||||
"Identifier"
|
||||
],
|
||||
"AWS::Cognito::UserPoolUser": [
|
||||
"DesiredDeliveryMediums",
|
||||
"ForceAliasCreation",
|
||||
"UserAttributes",
|
||||
"Username",
|
||||
"UserPoolId",
|
||||
"ValidationData",
|
||||
"ClientMetadata",
|
||||
"MessageAction"
|
||||
],
|
||||
"AWS::Cognito::UserPoolUserToGroupAttachment": [
|
||||
"UserPoolId",
|
||||
"GroupName",
|
||||
"Username"
|
||||
],
|
||||
"AWS::Config::ConfigRule": [
|
||||
"ConfigRuleName"
|
||||
],
|
||||
"AWS::DSQL::Cluster": [],
|
||||
"AWS::DynamoDB::GlobalTable": [
|
||||
"TableName"
|
||||
],
|
||||
@@ -449,13 +489,32 @@
|
||||
"AmiType",
|
||||
"Subnets"
|
||||
],
|
||||
"AWS::ElastiCache::CacheCluster": [
|
||||
"Port",
|
||||
"SnapshotArns",
|
||||
"SnapshotName",
|
||||
"CacheSubnetGroupName",
|
||||
"ClusterName",
|
||||
"Engine",
|
||||
"NetworkType"
|
||||
],
|
||||
"AWS::ElastiCache::ServerlessCache": [
|
||||
"ServerlessCacheName",
|
||||
"KmsKeyId",
|
||||
"SnapshotArnsToRestore",
|
||||
"SubnetIds",
|
||||
"ConnectionType",
|
||||
"NetworkType"
|
||||
"NetworkType",
|
||||
"ConnectionType"
|
||||
],
|
||||
"AWS::ElastiCache::SubnetGroup": [
|
||||
"CacheSubnetGroupName"
|
||||
],
|
||||
"AWS::ElastiCache::User": [
|
||||
"UserId",
|
||||
"UserName"
|
||||
],
|
||||
"AWS::ElastiCache::UserGroup": [
|
||||
"UserGroupId"
|
||||
],
|
||||
"AWS::ElasticLoadBalancingV2::Listener": [
|
||||
"LoadBalancerArn"
|
||||
@@ -477,6 +536,13 @@
|
||||
"Protocol",
|
||||
"IpAddressType"
|
||||
],
|
||||
"AWS::Events::ApiDestination": [
|
||||
"Name"
|
||||
],
|
||||
"AWS::Events::Archive": [
|
||||
"ArchiveName",
|
||||
"SourceArn"
|
||||
],
|
||||
"AWS::Events::EventBus": [
|
||||
"Name"
|
||||
],
|
||||
@@ -540,6 +606,10 @@
|
||||
"AWS::IoT::TopicRule": [
|
||||
"RuleName"
|
||||
],
|
||||
"AWS::KMS::Alias": [
|
||||
"AliasName"
|
||||
],
|
||||
"AWS::KMS::Key": [],
|
||||
"AWS::Kinesis::Stream": [
|
||||
"Name"
|
||||
],
|
||||
@@ -556,14 +626,11 @@
|
||||
"IcebergDestinationConfiguration/CatalogConfiguration",
|
||||
"SnowflakeDestinationConfiguration/SnowflakeVpcConfiguration"
|
||||
],
|
||||
"AWS::KMS::Alias": [
|
||||
"AliasName"
|
||||
],
|
||||
"AWS::KMS::Key": [],
|
||||
"AWS::Lambda::Alias": [
|
||||
"Name",
|
||||
"FunctionName"
|
||||
],
|
||||
"AWS::Lambda::CodeSigningConfig": [],
|
||||
"AWS::Lambda::EventInvokeConfig": [
|
||||
"FunctionName",
|
||||
"Qualifier"
|
||||
@@ -675,6 +742,7 @@
|
||||
"DBSystemId",
|
||||
"DatabaseName",
|
||||
"EngineMode",
|
||||
"WithExpressConfiguration",
|
||||
"KmsKeyId",
|
||||
"PubliclyAccessible",
|
||||
"RestoreToTime",
|
||||
@@ -744,8 +812,24 @@
|
||||
"Description"
|
||||
],
|
||||
"AWS::Redshift::ClusterSubnetGroup": [],
|
||||
"AWS::Redshift::EventSubscription": [
|
||||
"SubscriptionName"
|
||||
],
|
||||
"AWS::RedshiftServerless::Namespace": [
|
||||
"NamespaceName"
|
||||
],
|
||||
"AWS::RedshiftServerless::Workgroup": [
|
||||
"WorkgroupName",
|
||||
"NamespaceName"
|
||||
],
|
||||
"AWS::Route53::HealthCheck": [
|
||||
"HealthCheckConfig/Type",
|
||||
"HealthCheckConfig/MeasureLatency",
|
||||
"HealthCheckConfig/RequestInterval"
|
||||
],
|
||||
"AWS::Route53::HostedZone": [
|
||||
"Name"
|
||||
"Name",
|
||||
"DelegationSetId"
|
||||
],
|
||||
"AWS::Route53::RecordSet": [
|
||||
"HostedZoneName",
|
||||
@@ -777,22 +861,12 @@
|
||||
"VectorBucketName",
|
||||
"EncryptionConfiguration"
|
||||
],
|
||||
"AWS::Scheduler::ScheduleGroup": [
|
||||
"Name"
|
||||
],
|
||||
"AWS::SES::EmailIdentity": [
|
||||
"EmailIdentity"
|
||||
],
|
||||
"AWS::SecretsManager::Secret": [
|
||||
"Name"
|
||||
],
|
||||
"AWS::SecretsManager::SecretTargetAttachment": [
|
||||
"SecretId"
|
||||
],
|
||||
"AWS::Signer::SigningProfile": [
|
||||
"ProfileName",
|
||||
"PlatformId",
|
||||
"SignatureValidityPeriod"
|
||||
"AWS::SES::ReceiptRule": [
|
||||
"Rule/Name",
|
||||
"RuleSetName"
|
||||
],
|
||||
"AWS::SNS::Subscription": [
|
||||
"Endpoint",
|
||||
@@ -812,10 +886,50 @@
|
||||
"AWS::SSM::Parameter": [
|
||||
"Name"
|
||||
],
|
||||
"AWS::Scheduler::Schedule": [
|
||||
"Name"
|
||||
],
|
||||
"AWS::Scheduler::ScheduleGroup": [
|
||||
"Name"
|
||||
],
|
||||
"AWS::SecretsManager::Secret": [
|
||||
"Name"
|
||||
],
|
||||
"AWS::SecretsManager::SecretTargetAttachment": [
|
||||
"SecretId"
|
||||
],
|
||||
"AWS::ServiceDiscovery::HttpNamespace": [
|
||||
"Name"
|
||||
],
|
||||
"AWS::ServiceDiscovery::PrivateDnsNamespace": [
|
||||
"Vpc",
|
||||
"Name"
|
||||
],
|
||||
"AWS::ServiceDiscovery::PublicDnsNamespace": [
|
||||
"Name"
|
||||
],
|
||||
"AWS::ServiceDiscovery::Service": [
|
||||
"HealthCheckCustomConfig",
|
||||
"Name",
|
||||
"Type",
|
||||
"NamespaceId"
|
||||
],
|
||||
"AWS::Signer::SigningProfile": [
|
||||
"ProfileName",
|
||||
"PlatformId",
|
||||
"SignatureValidityPeriod"
|
||||
],
|
||||
"AWS::StepFunctions::StateMachine": [
|
||||
"StateMachineName",
|
||||
"StateMachineType"
|
||||
],
|
||||
"AWS::Transfer::Server": [
|
||||
"Domain"
|
||||
],
|
||||
"AWS::Transfer::User": [
|
||||
"ServerId",
|
||||
"UserName"
|
||||
],
|
||||
"AWS::WAFv2::IPSet": [
|
||||
"Name",
|
||||
"Scope"
|
||||
@@ -826,5 +940,9 @@
|
||||
"AWS::WAFv2::WebACL": [
|
||||
"Name",
|
||||
"Scope"
|
||||
],
|
||||
"AWS::WAFv2::WebACLAssociation": [
|
||||
"ResourceArn",
|
||||
"WebACLArn"
|
||||
]
|
||||
}
|
||||
+64
-1
@@ -1,8 +1,17 @@
|
||||
package io.floci.aws.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
@@ -10,6 +19,13 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class CfnCreateOnlyPropertiesTest {
|
||||
|
||||
private static final Path INVENTORY =
|
||||
Path.of("src/test/resources/cloudformation/supported-resource-types.tsv");
|
||||
|
||||
/** Inventory types with no registry schema; they are the only ones allowed to have no entry. */
|
||||
private static final Set<String> TYPES_WITHOUT_SCHEMA =
|
||||
Set.of("AWS::CDK::Metadata", "Custom::DynamoDBReplica");
|
||||
|
||||
@Test
|
||||
void s3VectorsCreateOnlyPropertiesMatchTheRegistrySchemas() {
|
||||
assertEquals(Set.of("DataType", "Dimension", "DistanceMetric", "EncryptionConfiguration", "IndexName",
|
||||
@@ -107,8 +123,11 @@ class CfnCreateOnlyPropertiesTest {
|
||||
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::AppConfig::Application", "Name"));
|
||||
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::AppConfig::Environment", "ApplicationId"));
|
||||
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::AppConfig::Environment", "Name"));
|
||||
assertEquals(Set.of("ApplicationId", "LocationUri", "Type"),
|
||||
assertEquals(Set.of("ApplicationId", "LocationUri"),
|
||||
CfnCreateOnlyProperties.getCreateOnlyProperties("AWS::AppConfig::ConfigurationProfile"));
|
||||
// Type is not create-only: the registry schema lists only ApplicationId and LocationUri, and the
|
||||
// AWS resource page gives Type "Update requires: No interruption".
|
||||
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::AppConfig::ConfigurationProfile", "Type"));
|
||||
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::AppConfig::ConfigurationProfile", "Name"));
|
||||
assertEquals(Set.of("Name", "ReplicateTo"),
|
||||
CfnCreateOnlyProperties.getCreateOnlyProperties("AWS::AppConfig::DeploymentStrategy"));
|
||||
@@ -154,4 +173,48 @@ class CfnCreateOnlyPropertiesTest {
|
||||
Set<String> unknownProps = CfnCreateOnlyProperties.getCreateOnlyProperties("Unknown::Type");
|
||||
assertTrue(unknownProps.isEmpty());
|
||||
}
|
||||
|
||||
/**
|
||||
* Every type floci provisions has an entry in create-only-properties.json, taken from its
|
||||
* registry schema, so the name heuristic in {@code isCreateOnly} is never what answers for a
|
||||
* supported type. A type with no schema is listed above with its reason and has no entry.
|
||||
*/
|
||||
@Test
|
||||
void everyInventoryTypeHasAnEntryExceptTheSchemalessOnes() throws IOException {
|
||||
Map<String, Set<String>> entries;
|
||||
try (InputStream in = getClass().getClassLoader()
|
||||
.getResourceAsStream("cloudformation/create-only-properties.json")) {
|
||||
entries = new ObjectMapper().readValue(in, new TypeReference<Map<String, Set<String>>>() {});
|
||||
}
|
||||
Set<String> missing = new TreeSet<>();
|
||||
for (String line : Files.readAllLines(INVENTORY)) {
|
||||
if (line.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
String type = line.split("\t", 2)[0];
|
||||
if (!entries.containsKey(type) && !TYPES_WITHOUT_SCHEMA.contains(type)) {
|
||||
missing.add(type);
|
||||
}
|
||||
}
|
||||
List<String> listedWithEntry = TYPES_WITHOUT_SCHEMA.stream().filter(entries::containsKey).sorted().toList();
|
||||
|
||||
assertEquals(Set.of(), missing,
|
||||
"Inventory types with no entry in create-only-properties.json: run make cfn-create-only-sync.");
|
||||
assertEquals(List.of(), listedWithEntry,
|
||||
"Types listed as schemaless that do have an entry: remove them from the list.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Registry schemas (CloudformationSchema.zip, us-east-1): aws-events-archive.json lists
|
||||
* createOnlyProperties ArchiveName and SourceArn only, so KmsKeyIdentifier is updatable
|
||||
* (the name heuristic answered true for any name ending in Identifier), and SourceArn is
|
||||
* create-only although no heuristic rule matches it.
|
||||
*/
|
||||
@Test
|
||||
void isCreateOnly_eventsArchiveFollowsTheRegistrySchema() {
|
||||
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::Events::Archive", "KmsKeyIdentifier"));
|
||||
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::Events::Archive", "SourceArn"));
|
||||
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::Events::Archive", "ArchiveName"));
|
||||
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::Events::Archive", "RetentionDays"));
|
||||
}
|
||||
}
|
||||
+252
@@ -1,14 +1,17 @@
|
||||
package io.floci.aws.services.cloudformation;
|
||||
|
||||
import io.floci.aws.core.common.XmlParser;
|
||||
import io.floci.aws.services.ses.SesReceiptRuleService;
|
||||
import io.floci.aws.testing.CfnStackWaits;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -29,6 +32,9 @@ class CloudFormationChangeSetDiffIntegrationTest {
|
||||
|
||||
private static final String SSM_CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
|
||||
@Inject
|
||||
SesReceiptRuleService ses;
|
||||
|
||||
private final List<String> stacksToDelete = new ArrayList<>();
|
||||
|
||||
@BeforeAll
|
||||
@@ -486,6 +492,70 @@ class CloudFormationChangeSetDiffIntegrationTest {
|
||||
.body(containsString("<Replacement>True</Replacement>"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Registry schema aws-cognito-userpooluser.json (CloudformationSchema.zip, us-east-1) lists
|
||||
* /properties/UserPoolId in createOnlyProperties; the resource page
|
||||
* aws-resource-cognito-userpooluser says "Update requires: Replacement" for UserPoolId.
|
||||
*/
|
||||
@Test
|
||||
void createOnlyPropertyChange_reportsReplacementTrue() {
|
||||
String stackName = "cs-diff-create-only-stack";
|
||||
stacksToDelete.add(stackName);
|
||||
|
||||
String initialTemplate = userPoolUserTemplate("PoolA");
|
||||
String changedTemplate = userPoolUserTemplate("PoolB");
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", initialTemplate)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE");
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "create-only-cs")
|
||||
.formParam("ChangeSetType", "UPDATE")
|
||||
.formParam("TemplateBody", changedTemplate)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", "create-only-cs")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<LogicalResourceId>U</LogicalResourceId>"))
|
||||
.body(containsString("<Replacement>True</Replacement>"));
|
||||
}
|
||||
|
||||
private static String userPoolUserTemplate(String poolLogicalId) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"PoolA": {"Type": "AWS::Cognito::UserPool", "Properties": {"UserPoolName": "cs-diff-pool-a"}},
|
||||
"PoolB": {"Type": "AWS::Cognito::UserPool", "Properties": {"UserPoolName": "cs-diff-pool-b"}},
|
||||
"U": {
|
||||
"Type": "AWS::Cognito::UserPoolUser",
|
||||
"Properties": {"UserPoolId": {"Ref": "%s"}, "Username": "cs-diff-user"}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(poolLogicalId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void ssmParameterValueDrift_isReportedAsAChange() {
|
||||
String stackName = "cs-diff-ssm-drift-stack";
|
||||
@@ -878,4 +948,186 @@ class CloudFormationChangeSetDiffIntegrationTest {
|
||||
.anyMatch(m -> "UnchangedQueue".equals(m.get("LogicalResourceId")));
|
||||
assertFalse(unchangedQueueIncluded);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registry schema aws-route53-healthcheck.json lists only /properties/HealthCheckConfig/Type,
|
||||
* /MeasureLatency and /RequestInterval in createOnlyProperties, so editing the Port inside
|
||||
* HealthCheckConfig is an in-place update and editing its Type is a replacement.
|
||||
*/
|
||||
@Test
|
||||
void nestedCreateOnlyPointer_replacesOnlyWhenTheNestedValueChanges() {
|
||||
String stackName = "cs-diff-nested-hc-stack";
|
||||
stacksToDelete.add(stackName);
|
||||
|
||||
createStack(stackName, healthCheckTemplate("HTTP", 80));
|
||||
|
||||
assertEquals("False", previewReplacement(stackName, "hc-port-cs", healthCheckTemplate("HTTP", 8080)).get("Check"));
|
||||
assertEquals("True", previewReplacement(stackName, "hc-type-cs", healthCheckTemplate("HTTPS", 80)).get("Check"));
|
||||
}
|
||||
|
||||
private static String healthCheckTemplate(String type, int port) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Check": {
|
||||
"Type": "AWS::Route53::HealthCheck",
|
||||
"Properties": {
|
||||
"HealthCheckConfig": {
|
||||
"Type": "%s", "IPAddress": "192.0.2.10", "Port": %d, "ResourcePath": "/x"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(type, port);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registry schema aws-ses-receiptrule.json lists /properties/Rule/Name and /properties/RuleSetName
|
||||
* in createOnlyProperties, but not Rule/Enabled: toggling Enabled is in place, renaming is not.
|
||||
*/
|
||||
@Test
|
||||
void sesReceiptRule_replacesOnRuleNameButNotOnEnabled() {
|
||||
String stackName = "cs-diff-nested-ses-stack";
|
||||
String ruleSet = "cs-diff-nested-ses-set";
|
||||
stacksToDelete.add(stackName);
|
||||
ses.createReceiptRuleSet(ruleSet, "us-east-1");
|
||||
try {
|
||||
createStack(stackName, receiptRuleTemplate(ruleSet, "rule-a", true));
|
||||
|
||||
assertEquals("False", previewReplacement(stackName, "ses-enabled-cs",
|
||||
receiptRuleTemplate(ruleSet, "rule-a", false)).get("Rule"));
|
||||
assertEquals("True", previewReplacement(stackName, "ses-name-cs",
|
||||
receiptRuleTemplate(ruleSet, "rule-b", true)).get("Rule"));
|
||||
} finally {
|
||||
deleteStackNow(stackName);
|
||||
ses.deleteReceiptRuleSet(ruleSet, "us-east-1");
|
||||
}
|
||||
}
|
||||
|
||||
private static String receiptRuleTemplate(String ruleSet, String name, boolean enabled) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Rule": {
|
||||
"Type": "AWS::SES::ReceiptRule",
|
||||
"Properties": {
|
||||
"RuleSetName": "%s",
|
||||
"Rule": {"Name": "%s", "Enabled": %s, "Recipients": ["example.com"]}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(ruleSet, name, enabled);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registry schema aws-batch-computeenvironment.json lists /properties/ComputeResources/SpotIamFleetRole
|
||||
* in createOnlyProperties and does not list ComputeResources/InstanceRole. AWS::IAM::Role RoleName is
|
||||
* create-only (aws-iam-role.json), so renaming the role replaces it. A compute environment that
|
||||
* references the replaced role under SpotIamFleetRole is replaced with it; one that references it only
|
||||
* under InstanceRole (same parent, not create-only) is updated in place.
|
||||
*/
|
||||
@Test
|
||||
void dependentIsReplacedOnlyWhenTheReferenceSitsUnderANestedCreateOnlyPointer() {
|
||||
String stackName = "cs-diff-nested-dep-stack";
|
||||
stacksToDelete.add(stackName);
|
||||
|
||||
createStack(stackName, roleAndComputeTemplate("cs-diff-nested-role-a"));
|
||||
|
||||
Map<String, String> replacement = previewReplacement(stackName, "dep-cs",
|
||||
roleAndComputeTemplate("cs-diff-nested-role-b"));
|
||||
assertEquals("True", replacement.get("Role"));
|
||||
assertEquals("True", replacement.get("CreateOnlyRef"));
|
||||
assertEquals("False", replacement.get("SiblingRef"));
|
||||
}
|
||||
|
||||
private static String roleAndComputeTemplate(String roleName) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Role": {
|
||||
"Type": "AWS::IAM::Role",
|
||||
"Properties": {
|
||||
"RoleName": "%s",
|
||||
"AssumeRolePolicyDocument": {"Version": "2012-10-17", "Statement": [
|
||||
{"Effect": "Allow", "Principal": {"Service": "batch.amazonaws.com"}, "Action": "sts:AssumeRole"}]}
|
||||
}
|
||||
},
|
||||
"CreateOnlyRef": {
|
||||
"Type": "AWS::Batch::ComputeEnvironment",
|
||||
"Properties": {
|
||||
"ComputeEnvironmentName": "cs-diff-nested-ce-1",
|
||||
"Type": "MANAGED",
|
||||
"ComputeResources": {"Type": "FARGATE", "MaxvCpus": 4, "Subnets": ["subnet-local"],
|
||||
"SecurityGroupIds": ["sg-local"], "SpotIamFleetRole": {"Ref": "Role"}}
|
||||
}
|
||||
},
|
||||
"SiblingRef": {
|
||||
"Type": "AWS::Batch::ComputeEnvironment",
|
||||
"Properties": {
|
||||
"ComputeEnvironmentName": "cs-diff-nested-ce-2",
|
||||
"Type": "MANAGED",
|
||||
"ComputeResources": {"Type": "FARGATE", "MaxvCpus": 4, "Subnets": ["subnet-local"],
|
||||
"SecurityGroupIds": ["sg-local"], "InstanceRole": {"Ref": "Role"}}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(roleName);
|
||||
}
|
||||
|
||||
private void createStack(String stackName, String template) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE");
|
||||
}
|
||||
|
||||
private void deleteStackNow(String stackName) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DeleteStack")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/");
|
||||
}
|
||||
|
||||
/** Creates an UPDATE change set and returns the Replacement value per logical id. */
|
||||
private Map<String, String> previewReplacement(String stackName, String changeSetName, String template) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", changeSetName)
|
||||
.formParam("ChangeSetType", "UPDATE")
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
String desc = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeChangeSet")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("ChangeSetName", changeSetName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().body().asString();
|
||||
|
||||
Map<String, String> result = new HashMap<>();
|
||||
for (Map<String, String> change : XmlParser.extractGroups(desc, "ResourceChange")) {
|
||||
result.put(change.get("LogicalResourceId"), change.get("Replacement"));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ AWS::CloudFront::OriginAccessControl Id OriginAccessControlConfig
|
||||
AWS::CloudFront::OriginRequestPolicy Id,LastModifiedTime OriginRequestPolicyConfig
|
||||
AWS::CloudFront::PublicKey CreatedTime,Id PublicKeyConfig
|
||||
AWS::CloudFront::ResponseHeadersPolicy Id,LastModifiedTime ResponseHeadersPolicyConfig
|
||||
AWS::CloudTrail::Trail Arn,SnsTopicArn AdvancedEventSelectors,AggregationConfigurations,CloudWatchLogsLogGroupArn,CloudWatchLogsRoleArn,EnableLogFileValidation,EventSelectors,IncludeGlobalServiceEvents,InsightSelectors,IsLogging,IsMultiRegionTrail,IsOrganizationTrail,KMSKeyId,S3BucketName,S3KeyPrefix,SnsTopicName,Tags,TrailName
|
||||
AWS::CloudTrail::Trail Arn,SnsTopicArn AdvancedEventSelectors,AggregationConfigurations,CloudWatchLogsLogGroupArn,CloudWatchLogsRoleArn,EnableLogFileValidation,EventSelectors,IncludeGlobalServiceEvents,InsightSelectors,IsLogging,IsMultiRegionTrail,IsOrganizationTrail,KMSKeyId,RecursiveLogging,S3BucketName,S3KeyPrefix,SnsTopicName,Tags,TrailName
|
||||
AWS::CloudWatch::Alarm Arn ActionConfiguration,ActionsEnabled,AlarmActions,AlarmDescription,AlarmName,ComparisonOperator,DatapointsToAlarm,Dimensions,EvaluateLowSampleCountPercentile,EvaluationCriteria,EvaluationInterval,EvaluationPeriods,EvaluationWindow,ExtendedStatistic,InsufficientDataActions,MetricName,Metrics,Namespace,OKActions,Period,Statistic,Tags,Threshold,ThresholdMetricId,TreatMissingData,Unit,WarmUpConfiguration
|
||||
AWS::CloudWatch::CompositeAlarm Arn ActionConfiguration,ActionsEnabled,ActionsSuppressor,ActionsSuppressorExtensionPeriod,ActionsSuppressorWaitPeriod,AlarmActions,AlarmDescription,AlarmName,AlarmRule,InsufficientDataActions,OKActions,Tags
|
||||
AWS::CloudWatch::Dashboard DashboardBody,DashboardName,Tags
|
||||
|
||||
|
@@ -140,6 +140,7 @@ AWS::CloudTrail::Trail CloudWatchLogsLogGroupArn accepted and ignored
|
||||
AWS::CloudTrail::Trail CloudWatchLogsRoleArn accepted and ignored
|
||||
AWS::CloudTrail::Trail InsightSelectors accepted and ignored
|
||||
AWS::CloudTrail::Trail KMSKeyId accepted and ignored
|
||||
AWS::CloudTrail::Trail RecursiveLogging accepted and ignored
|
||||
AWS::CloudTrail::Trail Tags accepted and ignored
|
||||
AWS::CloudWatch::Alarm ActionConfiguration accepted and ignored
|
||||
AWS::CloudWatch::Alarm EvaluateLowSampleCountPercentile accepted and ignored
|
||||
|
||||
|
@@ -0,0 +1,149 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regenerate src/main/resources/cloudformation/create-only-properties.json from CloudFormation's resource schemas.
|
||||
|
||||
`CfnCreateOnlyProperties` answers, for a change set, whether editing a property replaces the resource.
|
||||
For a resource type with an entry the answer is the type's `createOnlyProperties` in the CloudFormation
|
||||
registry, so the file states, for every resource type in `supported-resource-types.tsv`, that list with
|
||||
the `/properties/` prefix stripped:
|
||||
|
||||
{ "<resource type>": ["<property or nested path such as HealthCheckConfig/Type>", ...] }
|
||||
|
||||
Types are sorted, each list keeps the order the schema gives it, and an empty list means the schema has
|
||||
no create-only property (the class treats an empty entry as authoritative, not as a missing one). A type
|
||||
with no schema in the archive has no entry and is declared in SCHEMALESS, which is the set
|
||||
`regen_cfn_schema_surface.py` holds; any other inventory type without a schema fails the run by name.
|
||||
|
||||
The schemas are the ones AWS publishes for us-east-1, the same `describe-type` returns:
|
||||
|
||||
https://schema.cloudformation.us-east-1.amazonaws.com/CloudformationSchema.zip
|
||||
|
||||
The archive is live and keeps no older copy, so, as with `regen_cfn_property_types.py`, `--verify` is
|
||||
online and exits 2 when the archive cannot be read.
|
||||
|
||||
Run from anywhere in the repo:
|
||||
python3 tools/aws/regen_cfn_create_only.py # fetch and rewrite the vendored file
|
||||
python3 tools/aws/regen_cfn_create_only.py --verify # online: the vendored file matches AWS
|
||||
python3 tools/aws/regen_cfn_create_only.py --source-dir <dir of aws-<service>-<type>.json>
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import http.client
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from regen_cfn_schema_surface import SCHEMALESS, file_name, inventory_types
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
OUTPUT = REPO_ROOT / "src/main/resources/cloudformation/create-only-properties.json"
|
||||
INVENTORY = REPO_ROOT / "src/test/resources/cloudformation/supported-resource-types.tsv"
|
||||
ARCHIVE_URL = "https://schema.cloudformation.us-east-1.amazonaws.com/CloudformationSchema.zip"
|
||||
FETCH_TIMEOUT_SECONDS = 60
|
||||
POINTER_PREFIX = "/properties/"
|
||||
|
||||
|
||||
def create_only(schema: dict) -> list[str]:
|
||||
"""The schema's `createOnlyProperties` without the `/properties/` prefix, in the schema's order."""
|
||||
pointers = schema.get("createOnlyProperties", [])
|
||||
if not isinstance(pointers, list):
|
||||
raise ValueError("'createOnlyProperties' is not a list")
|
||||
names = []
|
||||
for pointer in pointers:
|
||||
if not isinstance(pointer, str) or not pointer.startswith(POINTER_PREFIX) \
|
||||
or pointer == POINTER_PREFIX or pointer.endswith("/"):
|
||||
raise ValueError(f"expected a '{POINTER_PREFIX}<name>' pointer, found {pointer!r}")
|
||||
names.append(pointer[len(POINTER_PREFIX):])
|
||||
return names
|
||||
|
||||
|
||||
def check_schema(resource_type: str, schema: object) -> None:
|
||||
"""Refuse a schema that is not the one for `resource_type`, so a stub or renamed file cannot pass as empty."""
|
||||
if not isinstance(schema, dict):
|
||||
raise ValueError(f"the schema for {resource_type} is not an object")
|
||||
if schema.get("typeName") != resource_type:
|
||||
raise ValueError(f"the schema for {resource_type} has typeName {schema.get('typeName')!r}")
|
||||
if not isinstance(schema.get("properties"), dict):
|
||||
raise ValueError(f"the schema for {resource_type} has no 'properties' object")
|
||||
|
||||
|
||||
def fetch_schemas(resource_types: list[str], source_dir: Path | None) -> tuple[dict[str, dict], str]:
|
||||
"""The schema of every resource type that has one, and where they came from."""
|
||||
schemas: dict[str, dict] = {}
|
||||
if source_dir is not None:
|
||||
for resource_type in resource_types:
|
||||
path = source_dir / file_name(resource_type)
|
||||
if path.exists():
|
||||
schemas[resource_type] = json.loads(path.read_text(encoding="utf-8"))
|
||||
return schemas, f"--source-dir {source_dir}"
|
||||
with urllib.request.urlopen(ARCHIVE_URL, timeout=FETCH_TIMEOUT_SECONDS) as response:
|
||||
archive = zipfile.ZipFile(io.BytesIO(response.read()))
|
||||
names = set(archive.namelist())
|
||||
for resource_type in resource_types:
|
||||
if file_name(resource_type) in names:
|
||||
schemas[resource_type] = json.loads(archive.read(file_name(resource_type)).decode("utf-8"))
|
||||
return schemas, ARCHIVE_URL
|
||||
|
||||
|
||||
def render(schemas: dict[str, dict]) -> str:
|
||||
document = {resource_type: create_only(schemas[resource_type]) for resource_type in sorted(schemas)}
|
||||
return json.dumps(document, indent=2) + "\n"
|
||||
|
||||
|
||||
def _shown(path: Path) -> Path:
|
||||
try:
|
||||
return path.resolve().relative_to(REPO_ROOT)
|
||||
except ValueError:
|
||||
return path
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--verify", action="store_true", help="online: the vendored file matches AWS's schemas")
|
||||
parser.add_argument("--source-dir", type=Path, default=None,
|
||||
help="read saved aws-<service>-<type>.json schemas instead of fetching the archive")
|
||||
parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS)
|
||||
parser.add_argument("--inventory", type=Path, default=INVENTORY, help=argparse.SUPPRESS)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
resource_types = inventory_types(args.inventory)
|
||||
try:
|
||||
schemas, provenance = fetch_schemas(resource_types, args.source_dir)
|
||||
except (OSError, ValueError, zipfile.BadZipFile, http.client.HTTPException) as e:
|
||||
# The gate could not run, which CI has to tell apart from having found a difference.
|
||||
print(f"error: could not read the CloudFormation resource schemas ({e})", file=sys.stderr)
|
||||
return 2
|
||||
schemaless = [t for t in resource_types if t not in schemas]
|
||||
undeclared = [t for t in schemaless if t not in SCHEMALESS]
|
||||
if undeclared:
|
||||
shown = ", ".join(undeclared[:5]) + (f" and {len(undeclared) - 5} more" if len(undeclared) > 5 else "")
|
||||
print(f"error: no schema for {shown} in {provenance}; nothing was written or verified. "
|
||||
f"Fix the directory, or declare a type with no schema in SCHEMALESS.", file=sys.stderr)
|
||||
return 1
|
||||
try:
|
||||
for resource_type in sorted(schemas):
|
||||
check_schema(resource_type, schemas[resource_type])
|
||||
document = render(schemas)
|
||||
except (AttributeError, TypeError, ValueError) as e:
|
||||
print(f"error: could not read the CloudFormation resource schemas ({e})", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
if args.verify:
|
||||
if not args.output.exists() or args.output.read_text(encoding="utf-8") != document:
|
||||
print(f"error: {_shown(args.output)} no longer matches {provenance}; run "
|
||||
f"'make cfn-create-only-sync' and commit the result.", file=sys.stderr)
|
||||
return 1
|
||||
print(f"{_shown(args.output)} matches {provenance}.")
|
||||
return 0
|
||||
|
||||
args.output.write_text(document, encoding="utf-8")
|
||||
print(f"wrote {_shown(args.output)} ({len(schemas)} types, from {provenance}); "
|
||||
f"no schema: {', '.join(schemaless) if schemaless else 'none'}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Tests for regen_cfn_create_only.
|
||||
|
||||
Run with: pytest tools/aws -q (or: make aws-data-test)
|
||||
|
||||
Interface assumed from the specification (floci-createonly-2026-11-12/design.md), same shape as
|
||||
regen_cfn_property_types.py:
|
||||
- module regen_cfn_create_only with main(argv) -> int, exit 0 ok, 1 verify mismatch or a missing
|
||||
schema, 2 when the schemas cannot be read;
|
||||
- flags --source-dir DIR (saved aws-<service>-<type>.json files), --output FILE, --verify;
|
||||
- module attribute INVENTORY: the tab-separated inventory file (type in column 1), patched here;
|
||||
- module attribute SCHEMALESS: the reasoned list of inventory types with no registry schema
|
||||
(a set or a type-to-reason dict; patched here with a dict), today AWS::CDK::Metadata and
|
||||
Custom::DynamoDBReplica;
|
||||
- the output is a plain JSON object, type name to list of paths, no metadata key (the Java
|
||||
loader reads it as Map<String, Set<String>>).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import regen_cfn_create_only as r
|
||||
|
||||
# Hand-written schemas; expected values below are written by hand from the specification.
|
||||
WIDGET = {
|
||||
"typeName": "AWS::Test::Widget",
|
||||
"properties": {"Name": {"type": "string"}},
|
||||
"createOnlyProperties": ["/properties/Name", "/properties/Network/Subnet/Id", "/properties/Zone"],
|
||||
}
|
||||
GADGET = {"typeName": "AWS::Test::Gadget", "properties": {"Label": {"type": "string"}}}
|
||||
|
||||
|
||||
def _setup(tmp_path, monkeypatch, types, schemas, schemaless):
|
||||
inventory = tmp_path / "inventory.tsv"
|
||||
inventory.write_text("".join(f"{t}\tSomeProvisioner\n" for t in types), encoding="utf-8")
|
||||
source = tmp_path / "schemas"
|
||||
source.mkdir()
|
||||
for name, schema in schemas.items():
|
||||
(source / (name.lower().replace("::", "-") + ".json")).write_text(json.dumps(schema), encoding="utf-8")
|
||||
monkeypatch.setattr(r, "INVENTORY", inventory)
|
||||
monkeypatch.setattr(r, "SCHEMALESS", schemaless)
|
||||
return source, tmp_path / "create-only.json"
|
||||
|
||||
|
||||
def test_paths_lose_the_properties_prefix_nested_paths_stay_and_no_list_means_empty(tmp_path, monkeypatch):
|
||||
source, output = _setup(tmp_path, monkeypatch,
|
||||
["AWS::Test::Gadget", "AWS::Test::Widget", "Custom::Reasoned"],
|
||||
{"AWS::Test::Widget": WIDGET, "AWS::Test::Gadget": GADGET},
|
||||
{"Custom::Reasoned": "emitted by a toolchain, no registry schema"})
|
||||
|
||||
assert r.main(["--source-dir", str(source), "--output", str(output)]) == 0
|
||||
|
||||
assert json.loads(output.read_text(encoding="utf-8")) == {
|
||||
"AWS::Test::Gadget": [],
|
||||
"AWS::Test::Widget": ["Name", "Network/Subnet/Id", "Zone"],
|
||||
}
|
||||
|
||||
|
||||
def test_a_type_without_a_schema_is_refused_unless_it_is_in_the_reasoned_list(tmp_path, monkeypatch, capsys):
|
||||
source, output = _setup(tmp_path, monkeypatch, ["AWS::Test::Gadget", "AWS::Test::Widget"],
|
||||
{"AWS::Test::Widget": WIDGET}, {})
|
||||
|
||||
assert r.main(["--source-dir", str(source), "--output", str(output)]) != 0
|
||||
assert "AWS::Test::Gadget" in capsys.readouterr().err
|
||||
assert not output.exists()
|
||||
|
||||
monkeypatch.setattr(r, "SCHEMALESS", {"AWS::Test::Gadget": "has no registry schema"})
|
||||
|
||||
assert r.main(["--source-dir", str(source), "--output", str(output)]) == 0
|
||||
assert json.loads(output.read_text(encoding="utf-8")) == {"AWS::Test::Widget": ["Name", "Network/Subnet/Id", "Zone"]}
|
||||
|
||||
|
||||
def test_verify_fails_on_a_hand_edited_entry(tmp_path, monkeypatch):
|
||||
source, output = _setup(tmp_path, monkeypatch, ["AWS::Test::Widget"], {"AWS::Test::Widget": WIDGET}, {})
|
||||
assert r.main(["--source-dir", str(source), "--output", str(output)]) == 0
|
||||
|
||||
assert r.main(["--verify", "--source-dir", str(source), "--output", str(output)]) == 0
|
||||
|
||||
edited = json.loads(output.read_text(encoding="utf-8"))
|
||||
edited["AWS::Test::Widget"].append("Extra")
|
||||
output.write_text(json.dumps(edited, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
|
||||
assert r.main(["--verify", "--source-dir", str(source), "--output", str(output)]) == 1
|
||||
Reference in new issue
Block a user