diff --git a/.github/workflows/cfn-schema-drift.yml b/.github/workflows/cfn-schema-drift.yml index f1a0f388ca..4bee5d26b8 100644 --- a/.github/workflows/cfn-schema-drift.yml +++ b/.github/workflows/cfn-schema-drift.yml @@ -1,5 +1,6 @@ name: CloudFormation Schema Drift -# Checks the vendored CloudFormation property types against the resource schemas AWS publishes. +# Checks the vendored CloudFormation property types, and the schema surface CfnSchemaCoverageTest +# 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. @@ -19,6 +20,9 @@ on: - 'src/main/resources/aws/cfn-property-types.json' - 'tools/aws/regen_cfn_property_types.py' - 'tools/aws/test_regen_cfn_property_types.py' + - 'src/test/resources/cloudformation/schema-surface.tsv' + - 'tools/aws/regen_cfn_schema_surface.py' + - 'tools/aws/test_regen_cfn_schema_surface.py' - '.github/workflows/cfn-schema-drift.yml' schedule: # Mondays at 06:10 UTC, beside the IAM data drift check. @@ -34,7 +38,7 @@ concurrency: jobs: cfn-schema-drift: - name: Vendored CloudFormation property types still match AWS + name: Vendored CloudFormation property types and schema surface still match AWS runs-on: ubuntu-latest timeout-minutes: 5 steps: @@ -48,3 +52,8 @@ jobs: # No dependency install: the generator is stdlib-only. - name: Check the vendored property types still match AWS's schemas run: make cfn-property-types-verify + + # Runs even when the property types check failed, so one run reports both drifts. + - name: Check the committed schema surface still matches AWS's schemas + if: always() + run: make cfn-schema-surface-verify diff --git a/AGENTS.md b/AGENTS.md index 1ac60dc94c..d10a5c190a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -375,6 +375,9 @@ the registry and stubs what nothing serves; never add type-specific code to it. 10. A schema `readOnlyProperties` entry you cannot set goes in `src/test/resources/cloudformation/getatt-attribute-gaps.tsv` with a reason; `CfnSchemaCoverageTest` requires every unset attribute to be fixed or recorded. + A new type also needs its row in `schema-surface.tsv` (same directory): run + `make cfn-schema-surface-sync`. A writable property the provisioner never reads goes in + `writable-property-gaps.tsv`. References: `SqsCfnProvisioner` (smallest), `Ec2LaunchTemplateCfnProvisioner` (update-in-place and replacement), `LogsCfnProvisioner` (reconcile-vs-replace update). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f474bcf800..c61208b70f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -248,6 +248,9 @@ service you need already has a `*CfnProvisioner`, add your type there; otherwise `src/test/resources/cloudformation/getatt-attribute-gaps.tsv` with the reason. `CfnSchemaCoverageTest` requires every unset attribute to be either fixed or recorded, so "not emulated" stays distinguishable from "forgotten". + A new type also needs its row in `schema-surface.tsv` (same directory): run + `make cfn-schema-surface-sync`. A writable property the provisioner never reads goes in + `writable-property-gaps.tsv`. `SqsCfnProvisioner` is the smallest reference implementation; `Ec2LaunchTemplateCfnProvisioner` shows update-in-place and replacement handling; `LogsCfnProvisioner` shows a full reconcile-vs-replace diff --git a/Makefile b/Makefile index 156a6eed19..4ca1f1de4b 100644 --- a/Makefile +++ b/Makefile @@ -74,6 +74,7 @@ PREFIX ?= $(HOME)/.local iam-action-resources-sync iam-action-resources-check iam-action-resources-verify \ 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 \ 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 \ @@ -722,6 +723,25 @@ cfn-property-types-verify: ## CI gate (online): the vendored CloudFormation prop cfn-property-types-test: ## Run the CloudFormation property type generator's unit tests $(PYTHON) -m pytest tools/aws/test_regen_cfn_property_types.py -q +cfn-schema-surface-sync: ## Regenerate src/test/resources/cloudformation/schema-surface.tsv from AWS's resource schemas (commit the result) + $(PYTHON) tools/aws/regen_cfn_schema_surface.py + +cfn-schema-surface-verify: ## CI gate (online): the committed CloudFormation schema surface must still match AWS's schemas + @$(PYTHON) tools/aws/regen_cfn_schema_surface.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 schema surface comes from."; \ + echo " Run 'make cfn-schema-surface-sync' and commit the result."; \ + exit 1; \ + fi + +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 + .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 diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 1d519b806a..4004dc3390 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -705,9 +705,11 @@ nested stacks and custom resources included, so it behaves as if the template le A resource type can accept a writable property from the registry schema and never read it. Those properties are listed with the reason in `src/test/resources/cloudformation/writable-property-gaps.tsv`. -Where the registry schema corpus is present under `local/aws/cfn-resource-schemas/us-east-1/` -(gitignored, so not in CI), `CfnSchemaCoverageTest` fails when a writable property is neither read -nor listed, and when a listed property has started to be read, so closing a gap deletes its row. +`CfnSchemaCoverageTest` runs in CI against `src/test/resources/cloudformation/schema-surface.tsv`, the +read-only attributes and writable properties of each supported type's registry schema. It fails when a +writable property is neither read nor listed, and when a listed property has started to be read, so +closing a gap deletes its row. A new type needs a row in that file: `make cfn-schema-surface-sync` +regenerates it from AWS's published schemas, and `cfn-schema-drift.yml` compares it weekly. On AppSync resources, a property the previous template declared and the new template drops is cleared on `UpdateStack`; one the stack never declared keeps the value set outside it. A few members go back to diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnSchemaCoverageTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnSchemaCoverageTest.java index 518beb78f7..2675a267ff 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnSchemaCoverageTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnSchemaCoverageTest.java @@ -1,7 +1,5 @@ package io.github.hectorvent.floci.services.cloudformation; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceProvisioner; import io.github.hectorvent.floci.testing.MainSources; import org.junit.jupiter.api.Test; @@ -17,7 +15,6 @@ import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TreeMap; @@ -27,6 +24,9 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Pins the two halves of what the CloudFormation registry schemas declare and Floci does not * implement: the {@code Fn::GetAtt} attributes it does not set, and the writable properties its @@ -38,6 +38,11 @@ import java.util.stream.Stream; * way: the template validates and the value goes nowhere. Recording the gaps makes each set a * ratchet: closing one deletes a row, and introducing one has to add a row where a reviewer sees it. * + *

The schemas are read from {@code schema-surface.tsv}, the part of them this test uses, committed + * so the check runs on every pull request. {@code make cfn-schema-surface-sync} regenerates it from + * AWS's published archive and {@code make cfn-schema-surface-verify} compares it, weekly in + * {@code cfn-schema-drift.yml}. + * *

Not a parity assertion. Several rows are attributes Floci cannot set because it does not * emulate the underlying behaviour, and each carries the reason. The property rows start as * {@code accepted and ignored} unless the service docs already describe the omission, and only @@ -55,7 +60,8 @@ class CfnSchemaCoverageTest { Path.of("src/test/resources/cloudformation/getatt-attribute-gaps.tsv"); private static final Path PROPERTY_GAPS = Path.of("src/test/resources/cloudformation/writable-property-gaps.tsv"); - private static final Path SCHEMA_DIR = Path.of("local/aws/cfn-resource-schemas/us-east-1"); + private static final Path SCHEMA_SURFACE = + Path.of("src/test/resources/cloudformation/schema-surface.tsv"); private static final Path PROVISIONERS = MainSources.packageDir(CfnResourceProvisioner.class); /** @@ -133,30 +139,54 @@ class CfnSchemaCoverageTest { "toCamelCase(resolved,", "requestBody(props, ctx)"); private static final String ALL_PROPERTIES = "*"; - private static final ObjectMapper MAPPER = new ObjectMapper(); + + /** What the registry schemas declare for one resource type, see {@link #schemaSurface}. */ + private record SchemaSurface(Set readOnly, Set writable) { } /** - * The check needs the schema corpus, which lives under the gitignored {@code local/}. Absent in - * CI, so this is a local correctness aid; the checked-in gaps file is what CI reviews. + * The committed surface has a row for each inventory type with a schema and for nothing else, so a + * new type cannot slip past the ratchet for want of a row. */ - private static boolean schemasAvailable() { - return Files.isDirectory(SCHEMA_DIR); + @Test + void schemaSurfaceCoversExactlyTheInventory() { + Set rows = schemaSurface().keySet(); + Set expected = new TreeSet<>(inventory().keySet()); + expected.removeAll(TYPES_WITHOUT_SCHEMA); + Set missing = new TreeSet<>(expected); + missing.removeAll(rows); + Set extra = new TreeSet<>(rows); + extra.removeAll(expected); + + if (!missing.isEmpty() || !extra.isEmpty()) { + throw new AssertionError(SCHEMA_SURFACE + " does not match " + INVENTORY + ". No row for: " + + missing + ". Row for a type that is not in the inventory or has no schema: " + extra + + ". Run 'make cfn-schema-surface-sync' and commit the result; a type with no registry " + + "schema is declared in TYPES_WITHOUT_SCHEMA."); + } + } + + @Test + void aDuplicateTypeRowIsRefused() { + AssertionError e = assertThrows(AssertionError.class, () -> parseSchemaSurface( + List.of("AWS::SQS::Queue\tQueueUrl\tDelaySeconds", "AWS::SQS::Queue\t\t"))); + assertTrue(e.getMessage().contains("AWS::SQS::Queue"), e.getMessage()); + } + + @Test + void anEmptyNameIsRefused() { + for (String row : List.of("AWS::SQS::Queue\ta,,b\t", "AWS::SQS::Queue\t\ta,", "AWS::SQS::Queue\t,a\t")) { + assertThrows(AssertionError.class, () -> parseSchemaSurface(List.of(row)), row); + } } @Test void recordedGapsMatchWhatTheProvisionersActuallySet() { - if (!schemasAvailable()) { - return; - } assertSameLines(render(recordedGaps()), render(actualGaps())); } /** A row that has been fixed, or was never real, must be deleted rather than left behind. */ @Test void everyRecordedGapIsStillReal() { - if (!schemasAvailable()) { - return; - } Map actual = actualGaps(); List stale = recordedGaps().keySet().stream() .filter(key -> !actual.containsKey(key)) @@ -185,9 +215,6 @@ class CfnSchemaCoverageTest { @Test void recordedPropertyGapsMatchWhatTheProvisionersActuallyRead() { - if (!schemasAvailable()) { - return; - } assertSameLines(render(recordedPropertyGaps()), render(actualPropertyGaps()), "The set of ignored writable schema properties changed.", "(a provisioner stopped reading a declared property, or a new type arrived with one " @@ -198,9 +225,6 @@ class CfnSchemaCoverageTest { /** A property a provisioner now reads must lose its row rather than keep claiming to be ignored. */ @Test void everyRecordedPropertyGapIsStillReal() { - if (!schemasAvailable()) { - return; - } Map actual = actualPropertyGaps(); List stale = recordedPropertyGaps().keySet().stream() .filter(key -> !actual.containsKey(key)) @@ -625,36 +649,22 @@ class CfnSchemaCoverageTest { return source.substring(open); } - /** No schema file: fine for a declared schema-less type, a failure naming the type otherwise. */ - private static Set missingSchema(String resourceType) { + /** No schema row: fine for a declared schema-less type, a failure naming the type otherwise. */ + private static SchemaSurface missingSchema(String resourceType) { if (!TYPES_WITHOUT_SCHEMA.contains(resourceType)) { - throw new AssertionError("No registry schema file for " + resourceType + " in " + SCHEMA_DIR - + ", so its attributes and properties would go unchecked. Fix the type name, or " - + "declare it in TYPES_WITHOUT_SCHEMA."); + throw new AssertionError("No registry schema row for " + resourceType + " in " + SCHEMA_SURFACE + + ", so its attributes and properties would go unchecked. Run " + + "'make cfn-schema-surface-sync', fix the type name, or declare it in TYPES_WITHOUT_SCHEMA."); } - return Set.of(); + return new SchemaSurface(Set.of(), Set.of()); } - /** Top-level read-only properties only: a nested pointer is not a GetAtt attribute name. */ + /** + * Top-level read-only properties only: a nested pointer is not a GetAtt attribute name. They are + * the attributes the schema declares. + */ private static Set schemaReadOnlyAttributes(String resourceType) { - Path schema = SCHEMA_DIR.resolve( - resourceType.replace("::", "-").toLowerCase(Locale.ROOT) + ".json"); - if (!Files.exists(schema)) { - return missingSchema(resourceType); - } - try { - JsonNode root = MAPPER.readTree(Files.readString(schema, StandardCharsets.UTF_8)); - Set attributes = new LinkedHashSet<>(); - for (JsonNode pointer : root.path("readOnlyProperties")) { - String[] parts = pointer.asText().split("/"); - if (parts.length == 3) { - attributes.add(parts[2]); - } - } - return attributes; - } catch (IOException e) { - throw new UncheckedIOException("Cannot read " + schema, e); - } + return surfaceOf(resourceType).readOnly(); } /** @@ -663,32 +673,67 @@ class CfnSchemaCoverageTest { * as nested pointers are for the attributes. */ private static Set schemaWritableProperties(String resourceType) { - Path schema = SCHEMA_DIR.resolve( - resourceType.replace("::", "-").toLowerCase(Locale.ROOT) + ".json"); - if (!Files.exists(schema)) { - return missingSchema(resourceType); - } + return surfaceOf(resourceType).writable(); + } + + private static SchemaSurface surfaceOf(String resourceType) { + SchemaSurface surface = schemaSurface().get(resourceType); + return surface != null ? surface : missingSchema(resourceType); + } + + /** + * The committed part of the registry schemas this test compares against, one row per type: + * "type<TAB>read-only attributes<TAB>writable properties", the names comma separated. + * Generated by {@code make cfn-schema-surface-sync}; see {@code tools/aws/regen_cfn_schema_surface.py}. + */ + private static Map schemaSurface() { try { - JsonNode root = MAPPER.readTree(Files.readString(schema, StandardCharsets.UTF_8)); - Set excluded = new HashSet<>(schemaReadOnlyAttributes(resourceType)); - for (JsonNode pointer : root.path("deprecatedProperties")) { - String[] parts = pointer.asText().split("/"); - if (parts.length == 3) { - excluded.add(parts[2]); - } - } - Set writable = new TreeSet<>(); - root.path("properties").fieldNames().forEachRemaining(name -> { - if (!excluded.contains(name)) { - writable.add(name); - } - }); - return writable; + return parseSchemaSurface(Files.readAllLines(SCHEMA_SURFACE, StandardCharsets.UTF_8)); } catch (IOException e) { - throw new UncheckedIOException("Cannot read " + schema, e); + throw new UncheckedIOException("Cannot read " + SCHEMA_SURFACE, e); } } + /** + * Parses the rows of the committed surface. A repeated type or an empty name is refused: a later row + * would silently replace an earlier one, emptying its checks, and an empty name matches nothing. + */ + static Map parseSchemaSurface(List lines) { + Map surface = new TreeMap<>(); + for (String line : lines) { + if (line.isBlank()) { + continue; + } + String[] parts = line.split("\t", -1); + if (parts.length != 3) { + throw new AssertionError("Expected 'typeattributesproperties' in " + + SCHEMA_SURFACE + " but found: " + line); + } + if (parts[0].isBlank()) { + throw new AssertionError("A row in " + SCHEMA_SURFACE + " has no type: " + line); + } + if (surface.put(parts[0], new SchemaSurface(names(parts[1], line), names(parts[2], line))) != null) { + throw new AssertionError("Two rows for " + parts[0] + " in " + SCHEMA_SURFACE + + "; the later would replace the earlier. Run 'make cfn-schema-surface-sync'."); + } + } + return surface; + } + + private static Set names(String commaSeparated, String line) { + if (commaSeparated.isEmpty()) { + return Set.of(); + } + Set names = new TreeSet<>(); + for (String name : commaSeparated.split(",", -1)) { + if (name.isBlank()) { + throw new AssertionError("An empty name in a row of " + SCHEMA_SURFACE + ": " + line); + } + names.add(name); + } + return names; + } + private static Map inventory() { Map types = new TreeMap<>(); try { diff --git a/src/test/resources/cloudformation/schema-surface.tsv b/src/test/resources/cloudformation/schema-surface.tsv new file mode 100644 index 0000000000..9d9cb3e3aa --- /dev/null +++ b/src/test/resources/cloudformation/schema-surface.tsv @@ -0,0 +1,200 @@ +AWS::ApiGateway::Account Id CloudWatchRoleArn +AWS::ApiGateway::ApiKey APIKeyId CustomerId,Description,Enabled,GenerateDistinctId,Name,StageKeys,Tags,Value +AWS::ApiGateway::Authorizer AuthorizerId AuthType,AuthorizerCredentials,AuthorizerResultTtlInSeconds,AuthorizerUri,IdentitySource,IdentityValidationExpression,Name,ProviderARNs,RestApiId,Type +AWS::ApiGateway::BasePathMapping BasePath,DomainName,RestApiId,Stage +AWS::ApiGateway::Deployment DeploymentId DeploymentCanarySettings,Description,RestApiId,StageDescription,StageName +AWS::ApiGateway::DomainName DistributionDomainName,DistributionHostedZoneId,DomainNameArn,RegionalDomainName,RegionalHostedZoneId CertificateArn,DomainName,EndpointAccessMode,EndpointConfiguration,MutualTlsAuthentication,OwnershipVerificationCertificateArn,RegionalCertificateArn,RoutingMode,SecurityPolicy,Tags +AWS::ApiGateway::GatewayResponse Id ResponseParameters,ResponseTemplates,ResponseType,RestApiId,StatusCode +AWS::ApiGateway::Method ApiKeyRequired,AuthorizationScopes,AuthorizationType,AuthorizerId,HttpMethod,Integration,MethodResponses,OperationName,RequestModels,RequestParameters,RequestValidatorId,ResourceId,RestApiId +AWS::ApiGateway::Resource ResourceId ParentId,PathPart,RestApiId +AWS::ApiGateway::RestApi RestApiId,RootResourceId ApiKeySourceType,BinaryMediaTypes,Body,BodyS3Location,CloneFrom,Description,DisableExecuteApiEndpoint,EndpointAccessMode,EndpointConfiguration,FailOnWarnings,MinimumCompressionSize,Mode,Name,Parameters,Policy,SecurityPolicy,Tags,Version +AWS::ApiGateway::Stage AccessLogSetting,CacheClusterEnabled,CacheClusterSize,CanarySetting,ClientCertificateId,DeploymentId,Description,DocumentationVersion,MethodSettings,RestApiId,StageName,Tags,TracingEnabled,Variables +AWS::ApiGateway::UsagePlan Id ApiStages,Description,Quota,Tags,Throttle,UsagePlanName +AWS::ApiGateway::UsagePlanKey Id KeyId,KeyType,UsagePlanId +AWS::ApiGatewayV2::Api ApiEndpoint,ApiId,ExecuteApiArn ApiKeySelectionExpression,BasePath,Body,BodyS3Location,CorsConfiguration,CredentialsArn,Description,DisableExecuteApiEndpoint,DisableSchemaValidation,FailOnWarnings,IpAddressType,Name,ProtocolType,RouteKey,RouteSelectionExpression,Tags,Target,Version +AWS::ApiGatewayV2::ApiMapping ApiMappingId ApiId,ApiMappingKey,DomainName,Stage +AWS::ApiGatewayV2::Authorizer AuthorizerId ApiId,AuthorizerCredentialsArn,AuthorizerPayloadFormatVersion,AuthorizerResultTtlInSeconds,AuthorizerType,AuthorizerUri,EnableSimpleResponses,IdentitySource,IdentityValidationExpression,JwtConfiguration,Name +AWS::ApiGatewayV2::Deployment DeploymentId ApiId,Description,StageName +AWS::ApiGatewayV2::DomainName DomainNameArn,RegionalDomainName,RegionalHostedZoneId DomainName,DomainNameConfigurations,MutualTlsAuthentication,RoutingMode,Tags +AWS::ApiGatewayV2::Integration IntegrationId ApiId,ConnectionId,ConnectionType,ContentHandlingStrategy,CredentialsArn,Description,IntegrationMethod,IntegrationSubtype,IntegrationType,IntegrationUri,PassthroughBehavior,PayloadFormatVersion,RequestParameters,RequestTemplates,ResponseParameters,TemplateSelectionExpression,TimeoutInMillis,TlsConfig +AWS::ApiGatewayV2::Route RouteId ApiId,ApiKeyRequired,AuthorizationScopes,AuthorizationType,AuthorizerId,ModelSelectionExpression,OperationName,RequestModels,RequestParameters,RouteKey,RouteResponseSelectionExpression,Target +AWS::ApiGatewayV2::Stage AccessLogSettings,ApiId,AutoDeploy,ClientCertificateId,DefaultRouteSettings,DeploymentId,Description,RouteSettings,StageName,StageVariables,Tags +AWS::ApiGatewayV2::VpcLink VpcLinkId Name,SecurityGroupIds,SubnetIds,Tags +AWS::AppConfig::Application ApplicationId Description,Name,Tags +AWS::AppConfig::ConfigurationProfile ConfigurationProfileId,KmsKeyArn ApplicationId,DeletionProtectionCheck,Description,KmsKeyIdentifier,LocationUri,Name,RetrievalRoleArn,Tags,Type,Validators +AWS::AppConfig::DeploymentStrategy Id DeploymentDurationInMinutes,Description,FinalBakeTimeInMinutes,GrowthFactor,GrowthType,Name,ReplicateTo,Tags +AWS::AppConfig::Environment EnvironmentId ApplicationId,DeletionProtectionCheck,Description,Monitors,Name,Tags +AWS::AppSync::ApiKey ApiKey,ApiKeyId,Arn ApiId,Description,Expires +AWS::AppSync::DataSource DataSourceArn ApiId,Description,DynamoDBConfig,EventBridgeConfig,HttpConfig,LambdaConfig,MetricsConfig,Name,OpenSearchServiceConfig,RelationalDatabaseConfig,ServiceRoleArn,Type +AWS::AppSync::FunctionConfiguration FunctionArn,FunctionId ApiId,Code,CodeS3Location,DataSourceName,Description,FunctionVersion,MaxBatchSize,Name,RequestMappingTemplate,RequestMappingTemplateS3Location,ResponseMappingTemplate,ResponseMappingTemplateS3Location,Runtime,SyncConfig +AWS::AppSync::GraphQLApi ApiId,Arn,GraphQLDns,GraphQLEndpointArn,GraphQLUrl,RealtimeDns,RealtimeUrl AdditionalAuthenticationProviders,ApiType,AuthenticationType,EnhancedMetricsConfig,EnvironmentVariables,IntrospectionConfig,LambdaAuthorizerConfig,LogConfig,MergedApiExecutionRoleArn,Name,OpenIDConnectConfig,OwnerContact,QueryDepthLimit,ResolverCountLimit,Tags,UserPoolConfig,Visibility,XrayEnabled +AWS::AppSync::GraphQLSchema Id ApiId,Definition,DefinitionS3Location +AWS::AppSync::Resolver ResolverArn ApiId,CachingConfig,Code,CodeS3Location,DataSourceName,FieldName,Kind,MaxBatchSize,MetricsConfig,PipelineConfig,RequestMappingTemplate,RequestMappingTemplateS3Location,ResponseMappingTemplate,ResponseMappingTemplateS3Location,Runtime,SyncConfig,TypeName +AWS::ApplicationAutoScaling::ScalableTarget Id MaxCapacity,MinCapacity,ResourceId,RoleARN,ScalableDimension,ScheduledActions,ServiceNamespace,SuspendedState,Tags +AWS::ApplicationAutoScaling::ScalingPolicy Arn PolicyName,PolicyType,PredictiveScalingPolicyConfiguration,ResourceId,ScalableDimension,ScalingTargetId,ServiceNamespace,StepScalingPolicyConfiguration,TargetTrackingScalingPolicyConfiguration +AWS::AutoScaling::AutoScalingGroup AutoScalingGroupARN AutoScalingGroupName,AvailabilityZoneDistribution,AvailabilityZoneIds,AvailabilityZoneImpairmentPolicy,AvailabilityZones,CapacityRebalance,CapacityReservationSpecification,Context,Cooldown,DefaultInstanceWarmup,DeletionProtection,DesiredCapacity,DesiredCapacityType,HealthCheckGracePeriod,HealthCheckType,InstanceId,InstanceLifecyclePolicy,InstanceMaintenancePolicy,LaunchConfigurationName,LaunchTemplate,LifecycleHookSpecificationList,LoadBalancerNames,MaxInstanceLifetime,MaxSize,MetricsCollection,MinSize,MixedInstancesPolicy,NewInstancesProtectedFromScaleIn,NotificationConfigurations,PlacementGroup,ServiceLinkedRoleARN,SkipZonalShiftValidation,Tags,TargetGroupARNs,TerminationPolicies,TrafficSources,VPCZoneIdentifier +AWS::AutoScaling::LaunchConfiguration AssociatePublicIpAddress,BlockDeviceMappings,ClassicLinkVPCId,ClassicLinkVPCSecurityGroups,EbsOptimized,IamInstanceProfile,ImageId,InstanceId,InstanceMonitoring,InstanceType,KernelId,KeyName,LaunchConfigurationName,MetadataOptions,PlacementTenancy,RamDiskId,SecurityGroups,SpotPrice,UserData +AWS::AutoScaling::LifecycleHook AutoScalingGroupName,DefaultResult,HeartbeatTimeout,LifecycleHookName,LifecycleTransition,NotificationMetadata,NotificationTargetARN,RoleARN +AWS::AutoScaling::ScalingPolicy Arn,PolicyName AdjustmentType,AutoScalingGroupName,Cooldown,EstimatedInstanceWarmup,MetricAggregationType,MinAdjustmentMagnitude,PolicyType,PredictiveScalingConfiguration,ScalingAdjustment,StepAdjustments,TargetTrackingConfiguration +AWS::Backup::BackupVault BackupVaultArn AccessPolicy,BackupVaultName,BackupVaultTags,EncryptionKeyArn,LockConfiguration,Notifications +AWS::Batch::ComputeEnvironment ComputeEnvironmentArn ComputeEnvironmentName,ComputeResources,Context,EcsSettings,EksConfiguration,ReplaceComputeEnvironment,ServiceRole,State,Tags,Type,UnmanagedvCpus,UpdatePolicy +AWS::Batch::JobDefinition JobDefinitionArn ConsumableResourceProperties,ContainerProperties,EcsProperties,EksProperties,JobDefinitionName,NodeProperties,Parameters,PlatformCapabilities,PropagateTags,ResourceRetentionPolicy,RetryStrategy,SchedulingPriority,Tags,Timeout,Type +AWS::Batch::JobQueue JobQueueArn ComputeEnvironmentOrder,JobQueueName,JobQueueType,JobStateTimeLimitActions,Priority,SchedulingPolicyArn,ServiceEnvironmentOrder,State,Tags +AWS::BedrockAgentCore::Memory CreatedAt,FailureReason,MemoryArn,MemoryId,Status,UpdatedAt Description,EncryptionKeyArn,EventExpiryDuration,IndexedKeys,MemoryExecutionRoleArn,MemoryStrategies,Name,NamespaceKeys,StreamDeliveryResources,Tags +AWS::BedrockAgentCore::Runtime AgentRuntimeArn,AgentRuntimeId,AgentRuntimeVersion,CreatedAt,FailureReason,LastUpdatedAt,Status,WorkloadIdentityDetails AgentRuntimeArtifact,AgentRuntimeName,AuthorizerConfiguration,CapacityProviderConfiguration,Description,EnvironmentVariables,FilesystemConfigurations,LifecycleConfiguration,NetworkConfiguration,PlatformVersion,ProtocolConfiguration,RequestHeaderConfiguration,RoleArn,Tags +AWS::BedrockAgentCore::RuntimeEndpoint AgentRuntimeArn,AgentRuntimeEndpointArn,CreatedAt,FailureReason,Id,LastUpdatedAt,LiveVersion,Status,TargetVersion AgentRuntimeId,AgentRuntimeVersion,Description,Name,Tags +AWS::CertificateManager::Certificate CertificateArn CertificateAuthorityArn,CertificateExport,CertificateTransparencyLoggingPreference,DomainName,DomainValidationOptions,KeyAlgorithm,SubjectAlternativeNames,Tags,ValidationMethod +AWS::CloudFormation::CustomResource Id ServiceTimeout,ServiceToken +AWS::CloudFront::CachePolicy Id,LastModifiedTime CachePolicyConfig +AWS::CloudFront::Distribution DomainName,Id DistributionConfig,Tags +AWS::CloudFront::Function FunctionARN,Stage AutoPublish,FunctionCode,FunctionConfig,FunctionMetadata,Name,Tags +AWS::CloudFront::KeyGroup Id,LastModifiedTime KeyGroupConfig +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::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 +AWS::CodeBuild::Project Arn Artifacts,AutoRetryLimit,BadgeEnabled,BuildBatchConfig,Cache,ConcurrentBuildLimit,Description,EncryptionKey,Environment,FileSystemLocations,LogsConfig,Name,QueuedTimeoutInMinutes,ResourceAccessRole,SecondaryArtifacts,SecondarySourceVersions,SecondarySources,ServiceRole,Source,SourceVersion,Tags,TimeoutInMinutes,Triggers,Visibility,VpcConfig +AWS::CodePipeline::CustomActionType Id Category,ConfigurationProperties,InputArtifactDetails,OutputArtifactDetails,Provider,Settings,Tags,Version +AWS::CodePipeline::Pipeline Arn,Version ArtifactStore,ArtifactStores,DisableInboundStageTransitions,ExecutionMode,Name,PipelineType,RestartExecutionOnUpdate,RoleArn,Stages,Tags,Triggers,Variables +AWS::CodePipeline::Webhook Id,Url Authentication,AuthenticationConfiguration,Filters,Name,RegisterWithThirdParty,Tags,TargetAction,TargetPipeline,TargetPipelineVersion +AWS::Cognito::UserPool Arn,ProviderName,ProviderURL,UserPoolId AccountRecoverySetting,AdminCreateUserConfig,AliasAttributes,AutoVerifiedAttributes,DeletionProtection,DeviceConfiguration,EmailAuthenticationMessage,EmailAuthenticationSubject,EmailConfiguration,EmailVerificationMessage,EmailVerificationSubject,EnabledMfas,IssuerConfiguration,KeyConfiguration,LambdaConfig,MfaConfiguration,Policies,Schema,SmsAuthenticationMessage,SmsConfiguration,SmsVerificationMessage,UserAttributeUpdateSettings,UserPoolAddOns,UserPoolName,UserPoolTags,UserPoolTier,UsernameAttributes,UsernameConfiguration,VerificationMessageTemplate,WebAuthnFactorConfiguration,WebAuthnRelyingPartyID,WebAuthnUserVerification +AWS::Cognito::UserPoolClient ClientId,ClientSecret,Name AccessTokenValidity,AllowedOAuthFlows,AllowedOAuthFlowsUserPoolClient,AllowedOAuthScopes,AnalyticsConfiguration,AuthSessionValidity,CallbackURLs,ClientName,DefaultRedirectURI,EnablePropagateAdditionalUserContextData,EnableTokenRevocation,ExplicitAuthFlows,GenerateSecret,IdTokenValidity,LogoutURLs,PreventUserExistenceErrors,ReadAttributes,RefreshTokenRotation,RefreshTokenValidity,SupportedIdentityProviders,TokenValidityUnits,UserPoolId,WriteAttributes +AWS::Cognito::UserPoolDomain CloudFrontDistribution CustomDomainConfig,Domain,ManagedLoginVersion,Routing,UserPoolId +AWS::Cognito::UserPoolGroup Description,GroupName,Precedence,RoleArn,UserPoolId +AWS::Cognito::UserPoolResourceServer Identifier,Name,Scopes,UserPoolId +AWS::Cognito::UserPoolUser ClientMetadata,DesiredDeliveryMediums,ForceAliasCreation,MessageAction,UserAttributes,UserPoolId,Username,ValidationData +AWS::Cognito::UserPoolUserToGroupAttachment GroupName,UserPoolId,Username +AWS::Config::ConfigRule Arn,ConfigRuleId Compliance,ConfigRuleName,Description,EvaluationModes,InputParameters,MaximumExecutionFrequency,Scope,Source +AWS::DSQL::Cluster CreationTime,EncryptionDetails,Endpoint,Identifier,PolicyVersion,ResourceArn,Status,VpcEndpoint,VpcEndpointServiceName DeletionProtectionEnabled,KmsEncryptionKey,MultiRegionProperties,PolicyDocument,Tags +AWS::DynamoDB::GlobalTable Arn,StreamArn,TableId AttributeDefinitions,BillingMode,GlobalSecondaryIndexes,GlobalTableSourceArn,GlobalTableWitnesses,KeySchema,LocalSecondaryIndexes,MultiRegionConsistency,ReadOnDemandThroughputSettings,ReadProvisionedThroughputSettings,Replicas,SSESpecification,StreamSpecification,TableName,TableType,TimeToLiveSpecification,VectorIndexes,WarmThroughput,WriteOnDemandThroughputSettings,WriteProvisionedThroughputSettings +AWS::DynamoDB::Table Arn,StreamArn AttributeDefinitions,BillingMode,ContributorInsightsSpecification,DeletionProtectionEnabled,GlobalSecondaryIndexes,ImportSourceSpecification,KeySchema,KinesisStreamSpecification,LocalSecondaryIndexes,OnDemandThroughput,PointInTimeRecoverySpecification,ProvisionedThroughput,ResourcePolicy,SSESpecification,StreamSpecification,TableClass,TableName,Tags,TimeToLiveSpecification,VectorIndexes,WarmThroughput +AWS::EC2::EIP AllocationId,PublicIp Address,Domain,InstanceId,IpamPoolId,NetworkBorderGroup,PublicIpv4Pool,Tags,TransferAddress +AWS::EC2::FlowLog Id DeliverCrossAccountRole,DeliverLogsPermissionArn,DestinationOptions,LogDestination,LogDestinationType,LogFormat,LogGroupName,MaxAggregationInterval,ResourceId,ResourceType,TagFieldSpecifications,Tags,TrafficType +AWS::EC2::Instance InstanceId,PrivateDnsName,PrivateIp,PublicDnsName,PublicIp,State,VpcId AdditionalInfo,Affinity,AvailabilityZone,BlockDeviceMappings,CpuOptions,CreditSpecification,DisableApiTermination,EbsOptimized,ElasticGpuSpecifications,ElasticInferenceAccelerators,EnclaveOptions,HibernationOptions,HostId,HostResourceGroupArn,IamInstanceProfile,ImageId,InstanceInitiatedShutdownBehavior,InstanceType,Ipv6AddressCount,Ipv6Addresses,KernelId,KeyName,LaunchTemplate,LicenseSpecifications,MetadataOptions,Monitoring,NetworkInterfaces,PlacementGroupName,PrivateDnsNameOptions,PrivateIpAddress,PropagateTagsToVolumeOnCreation,RamdiskId,SecurityGroupIds,SecurityGroups,SourceDestCheck,SsmAssociations,SubnetId,Tags,Tenancy,UserData,Volumes +AWS::EC2::InternetGateway InternetGatewayId Tags +AWS::EC2::KeyPair KeyFingerprint,KeyPairId KeyFormat,KeyName,KeyType,PublicKeyMaterial,Tags +AWS::EC2::LaunchTemplate DefaultVersionNumber,LatestVersionNumber,LaunchTemplateId LaunchTemplateData,LaunchTemplateName,TagSpecifications,VersionDescription +AWS::EC2::NatGateway AutoProvisionZones,AutoScalingIps,EniId,NatGatewayId,RouteTableId AllocationId,AvailabilityMode,AvailabilityZoneAddresses,ConnectivityType,MaxDrainDurationSeconds,PrivateIpAddress,SecondaryAllocationIds,SecondaryPrivateIpAddressCount,SecondaryPrivateIpAddresses,SubnetId,Tags,VpcId +AWS::EC2::NetworkAcl Id Tags,VpcId +AWS::EC2::NetworkAclEntry Id CidrBlock,Egress,Icmp,Ipv6CidrBlock,NetworkAclId,PortRange,Protocol,RuleAction,RuleNumber +AWS::EC2::PrefixList Arn,OwnerId,PrefixListId,Version AddressFamily,Entries,MaxEntries,PrefixListName,Tags +AWS::EC2::Route CidrBlock CarrierGatewayId,CoreNetworkArn,DestinationCidrBlock,DestinationIpv6CidrBlock,DestinationPrefixListId,EgressOnlyInternetGatewayId,GatewayId,InstanceId,LocalGatewayId,NatGatewayId,NetworkInterfaceId,OdbNetworkArn,RouteTableId,TransitGatewayId,VpcEndpointId,VpcPeeringConnectionId +AWS::EC2::RouteTable RouteTableId Tags,VpcId +AWS::EC2::SecurityGroup GroupId,Id GroupDescription,GroupName,SecurityGroupEgress,SecurityGroupIngress,Tags,VpcId +AWS::EC2::SecurityGroupEgress Id CidrIp,CidrIpv6,Description,DestinationPrefixListId,DestinationSecurityGroupId,FromPort,GroupId,IpProtocol,ToPort +AWS::EC2::SecurityGroupIngress Id CidrIp,CidrIpv6,Description,FromPort,GroupId,GroupName,IpProtocol,SourcePrefixListId,SourceSecurityGroupId,SourceSecurityGroupName,SourceSecurityGroupOwnerId,ToPort +AWS::EC2::Subnet BlockPublicAccessStates,Ipv6CidrBlocks,NetworkAclAssociationId,SubnetId AssignIpv6AddressOnCreation,AvailabilityZone,AvailabilityZoneId,CidrBlock,EnableDns64,EnableLniAtDeviceIndex,Ipv4IpamPoolId,Ipv4NetmaskLength,Ipv6CidrBlock,Ipv6IpamPoolId,Ipv6Native,Ipv6NetmaskLength,MapPublicIpOnLaunch,OutpostArn,PrivateDnsNameOptionsOnLaunch,Tags,VpcId +AWS::EC2::SubnetNetworkAclAssociation AssociationId NetworkAclId,SubnetId +AWS::EC2::SubnetRouteTableAssociation Id RouteTableId,SubnetId +AWS::EC2::VPC CidrBlockAssociations,DefaultNetworkAcl,DefaultSecurityGroup,Ipv6CidrBlocks,VpcId CidrBlock,EnableDnsHostnames,EnableDnsSupport,InstanceTenancy,Ipv4IpamPoolId,Ipv4NetmaskLength,Tags,VpcEncryptionControl +AWS::EC2::VPCEndpoint CreationTimestamp,DnsEntries,Id,NetworkInterfaceIds DnsOptions,IpAddressType,PolicyDocument,PrivateDnsEnabled,ResourceConfigurationArn,RouteTableIds,SecurityGroupIds,ServiceName,ServiceNetworkArn,ServiceRegion,SubnetIds,Tags,VpcEndpointType,VpcId +AWS::EC2::VPCGatewayAttachment AttachmentType InternetGatewayId,VpcId,VpnGatewayId +AWS::ECR::Repository Arn,RepositoryUri EmptyOnDelete,EncryptionConfiguration,ImageScanningConfiguration,ImageTagMutability,ImageTagMutabilityExclusionFilters,LifecyclePolicy,RepositoryName,RepositoryPolicyText,Tags +AWS::ECS::CapacityProvider AutoScalingGroupProvider,ClusterName,ManagedInstancesProvider,Name,Tags +AWS::ECS::Cluster Arn CapacityProviders,ClusterName,ClusterSettings,Configuration,DefaultCapacityProviderStrategy,ServiceConnectDefaults,Tags +AWS::ECS::ClusterCapacityProviderAssociations CapacityProviders,Cluster,DefaultCapacityProviderStrategy +AWS::ECS::Service Name,ServiceArn AvailabilityZoneRebalancing,CapacityProviderStrategy,Cluster,DeploymentConfiguration,DeploymentController,DesiredCount,EnableECSManagedTags,EnableExecuteCommand,ForceNewDeployment,GatewayConnectors,HealthCheckGracePeriodSeconds,LaunchType,LoadBalancers,Monitoring,NetworkConfiguration,PlacementConstraints,PlacementStrategies,PlatformVersion,PropagateTags,Role,SchedulingStrategy,ServiceConnectConfiguration,ServiceName,ServiceRegistries,Tags,TaskDefinition,VolumeConfigurations,VpcLatticeConfigurations +AWS::ECS::TaskDefinition TaskDefinitionArn ContainerDefinitions,Cpu,EnableFaultInjection,EphemeralStorage,ExecutionRoleArn,Family,IpcMode,Memory,NetworkMode,PidMode,PlacementConstraints,ProxyConfiguration,RequiresCompatibilities,RuntimePlatform,Tags,TaskRoleArn,Volumes +AWS::EKS::Cluster Arn,CertificateAuthorityData,ClusterSecurityGroupId,EncryptionConfigKeyArn,Endpoint,Id,OpenIdConnectIssuerUrl AccessConfig,ActiveCertificateAuthorityId,BootstrapSelfManagedAddons,CertificateAuthority,ComputeConfig,ControlPlaneScalingConfig,DeletionProtection,EncryptionConfig,Force,KubeApiServerConfig,KubeControllerManagerConfig,KubeSchedulerConfig,KubernetesNetworkConfig,Logging,Name,OutpostConfig,RemoteNetworkConfig,ResourcesVpcConfig,RoleArn,RollbackConfig,StorageConfig,Tags,UpgradePolicy,Version,ZonalShiftConfig +AWS::EKS::Nodegroup Arn,Id AmiType,CapacityType,ClusterName,DiskSize,ForceUpdateEnabled,InstanceTypes,Labels,LaunchTemplate,NodeRepairConfig,NodeRole,NodegroupName,ReleaseVersion,RemoteAccess,ScalingConfig,Subnets,Tags,Taints,UpdateConfig,Version,WarmPoolConfig +AWS::ElastiCache::CacheCluster ConfigurationEndpoint,RedisEndpoint AZMode,AutoMinorVersionUpgrade,CacheNodeType,CacheParameterGroupName,CacheSubnetGroupName,ClusterName,Engine,EngineVersion,IpDiscovery,LogDeliveryConfigurations,NetworkType,NotificationTopicArn,NumCacheNodes,Port,PreferredAvailabilityZone,PreferredAvailabilityZones,PreferredMaintenanceWindow,SnapshotArns,SnapshotName,SnapshotRetentionLimit,SnapshotWindow,Tags,TransitEncryptionEnabled,VpcSecurityGroupIds +AWS::ElastiCache::ServerlessCache ARN,CreateTime,FullEngineVersion,Status CacheUsageLimits,ConnectionType,DailySnapshotTime,Description,Endpoint,Engine,FinalSnapshotName,KmsKeyId,MajorEngineVersion,NetworkType,ReaderEndpoint,SecurityGroupIds,ServerlessCacheName,SnapshotArnsToRestore,SnapshotRetentionLimit,SubnetIds,Tags,UserGroupId +AWS::ElastiCache::SubnetGroup CacheSubnetGroupName,Description,SubnetIds,Tags +AWS::ElastiCache::User Arn,Status AccessString,AuthenticationMode,Engine,NoPasswordRequired,Passwords,Tags,UserId,UserName +AWS::ElastiCache::UserGroup Arn,Status Engine,Tags,UserGroupId,UserIds +AWS::ElasticLoadBalancingV2::Listener ListenerArn AlpnPolicy,Certificates,DefaultActions,ListenerAttributes,LoadBalancerArn,MutualAuthentication,Port,Protocol,SslPolicy,Tags +AWS::ElasticLoadBalancingV2::ListenerRule IsDefault,RuleArn Actions,Conditions,ListenerArn,Priority,Tags,Transforms +AWS::ElasticLoadBalancingV2::LoadBalancer CanonicalHostedZoneID,DNSName,LoadBalancerArn,LoadBalancerFullName,LoadBalancerName EnableCapacityReservationProvisionStabilize,EnablePrefixForIpv6SourceNat,EnforceSecurityGroupInboundRulesOnPrivateLinkTraffic,IpAddressType,Ipv4IpamPoolId,LoadBalancerAttributes,MinimumLoadBalancerCapacity,Name,Scheme,SecurityGroups,SubnetMappings,Subnets,Tags,Type +AWS::ElasticLoadBalancingV2::TargetGroup LoadBalancerArns,TargetGroupArn,TargetGroupFullName,TargetGroupName HealthCheckEnabled,HealthCheckIntervalSeconds,HealthCheckPath,HealthCheckPort,HealthCheckProtocol,HealthCheckTimeoutSeconds,HealthyThresholdCount,IpAddressType,Matcher,Name,Port,Protocol,ProtocolVersion,Tags,TargetControlPort,TargetGroupAttributes,TargetType,Targets,UnhealthyThresholdCount,VpcId +AWS::Events::ApiDestination Arn,ArnForPolicy ConnectionArn,Description,HttpMethod,InvocationEndpoint,InvocationRateLimitPerSecond,Name +AWS::Events::Archive Arn ArchiveName,Description,EventPattern,KmsKeyIdentifier,RetentionDays,SourceArn +AWS::Events::EventBus Arn DeadLetterConfig,Description,EventSourceName,KmsKeyIdentifier,LogConfig,Name,Policy,Tags +AWS::Events::EventBusPolicy EventBusName,Statement,StatementId +AWS::Events::Rule Arn,RuleName Description,EventBusName,EventPattern,Name,RoleArn,ScheduleExpression,State,Tags,Targets +AWS::GuardDuty::MalwareProtectionPlan Arn,CreatedAt,MalwareProtectionPlanId,Status,StatusReasons Actions,ProtectedResource,Role,Tags +AWS::IAM::AccessKey Id,SecretAccessKey Serial,Status,UserName +AWS::IAM::InstanceProfile Arn InstanceProfileName,Path,Roles +AWS::IAM::ManagedPolicy AttachmentCount,CreateDate,DefaultVersionId,IsAttachable,PermissionsBoundaryUsageCount,PolicyArn,PolicyId,UpdateDate Description,Groups,ManagedPolicyName,Path,PolicyDocument,Roles,Users +AWS::IAM::Policy Id Groups,PolicyDocument,PolicyName,Roles,Users +AWS::IAM::Role Arn,RoleId AssumeRolePolicyDocument,Description,ManagedPolicyArns,MaxSessionDuration,Path,PermissionsBoundary,Policies,RoleName,Tags +AWS::IAM::User Arn Groups,LoginProfile,ManagedPolicyArns,Path,PermissionsBoundary,Policies,Tags,UserName +AWS::IoT::Authorizer Arn AuthorizerFunctionArn,AuthorizerName,EnableCachingForHttp,SigningDisabled,Status,Tags,TokenKeyName,TokenSigningPublicKeys +AWS::IoT::DomainConfiguration Arn,DomainType,ServerCertificates ApplicationProtocol,AuthenticationType,AuthorizerConfig,ClientCertificateConfig,DomainConfigurationName,DomainConfigurationStatus,DomainName,ServerCertificateArns,ServerCertificateConfig,ServiceType,Tags,TlsConfig,ValidationCertificateArn +AWS::IoT::Policy Arn,Id PolicyDocument,PolicyName,Tags +AWS::IoT::Thing Arn,Id AttributePayload,ThingName +AWS::IoT::TopicRule Arn RuleName,Tags,TopicRulePayload +AWS::KMS::Alias AliasName,TargetKeyId +AWS::KMS::Key Arn,KeyId BypassPolicyLockoutSafetyCheck,Description,EnableKeyRotation,Enabled,KeyPolicy,KeySpec,KeyUsage,MultiRegion,Origin,PendingWindowInDays,RotationPeriodInDays,Tags +AWS::Kinesis::Stream Arn,WarmThroughputObject DesiredShardLevelMetrics,MaxRecordSizeInKiB,Name,RecordDistributionStrategy,RetentionPeriodHours,ShardCount,StreamEncryption,StreamModeDetails,Tags,WarmThroughputMiBps +AWS::KinesisFirehose::DeliveryStream Arn AmazonOpenSearchServerlessDestinationConfiguration,AmazonopensearchserviceDestinationConfiguration,DatabaseSourceConfiguration,DeliveryStreamEncryptionConfigurationInput,DeliveryStreamName,DeliveryStreamType,DirectPutSourceConfiguration,ElasticsearchDestinationConfiguration,ExtendedS3DestinationConfiguration,HttpEndpointDestinationConfiguration,IcebergDestinationConfiguration,KinesisStreamSourceConfiguration,MSKSourceConfiguration,RedshiftDestinationConfiguration,S3DestinationConfiguration,SnowflakeDestinationConfiguration,SplunkDestinationConfiguration,Tags +AWS::Lambda::Alias AliasArn Description,FunctionName,FunctionVersion,Name,ProvisionedConcurrencyConfig,RoutingConfig +AWS::Lambda::EventInvokeConfig DestinationConfig,FunctionName,MaximumEventAgeInSeconds,MaximumRetryAttempts,Qualifier +AWS::Lambda::EventSourceMapping EventSourceMappingArn,Id AmazonManagedKafkaEventSourceConfig,BatchSize,BisectBatchOnFunctionError,DestinationConfig,DocumentDBEventSourceConfig,Enabled,EventSourceArn,FilterCriteria,FunctionName,FunctionResponseTypes,KmsKeyArn,LoggingConfig,MaximumBatchingWindowInSeconds,MaximumRecordAgeInSeconds,MaximumRetryAttempts,MetricsConfig,ParallelizationFactor,ProvisionedPollerConfig,Queues,ScalingConfig,SelfManagedEventSource,SelfManagedKafkaEventSourceConfig,SourceAccessConfigurations,StartingPosition,StartingPositionTimestamp,Tags,Topics,TumblingWindowInSeconds +AWS::Lambda::Function Arn,SnapStartResponse Architectures,CapacityProviderConfig,Code,CodeSigningConfigArn,DeadLetterConfig,Description,DurableConfig,Environment,EphemeralStorage,FileSystemConfigs,FunctionName,FunctionScalingConfig,Handler,ImageConfig,KmsKeyArn,Layers,LoggingConfig,MemorySize,PackageType,PublishToLatestPublished,RecursiveLoop,ReservedConcurrentExecutions,Role,Runtime,RuntimeManagementConfig,SnapStart,Tags,TenancyConfig,Timeout,TracingConfig,VpcConfig +AWS::Lambda::LayerVersion LayerVersionArn CompatibleArchitectures,CompatibleRuntimes,Content,Description,LayerName,LicenseInfo +AWS::Lambda::MicrovmImage CreatedAt,ImageArn,LatestActiveImageVersion,LatestFailedImageVersion,State,UpdatedAt AdditionalOsCapabilities,BaseImageArn,BaseImageVersion,BuildRoleArn,CodeArtifact,CpuConfigurations,Description,EgressNetworkConnectors,EnvironmentVariables,Hooks,Logging,Name,Resources,Tags +AWS::Lambda::NetworkConnector Arn,LatestVersion,LatestVersionArn,State Configuration,Name,OperatorRole,Tags +AWS::Lambda::Permission Id Action,EventSourceToken,FunctionName,FunctionUrlAuthType,InvokedViaFunctionUrl,Principal,PrincipalOrgID,SourceAccount,SourceArn +AWS::Lambda::Url FunctionArn,FunctionUrl AuthType,Cors,InvokeMode,Qualifier,TargetFunctionArn +AWS::Lambda::Version FunctionArn,Version CodeSha256,Description,FunctionName,FunctionScalingConfig,ProvisionedConcurrencyConfig,RuntimePolicy +AWS::Lambda::WebFunction CreatedAt,FunctionArn,State,StateReason,UpdatedAt FunctionName,Tags +AWS::Lambda::WebFunctionEndpoint CreatedAt,DomainName,EndpointArn,FunctionArn,RegionalEndpoints,State,StateReason,UpdateStatus,UpdateStatusReason,UpdatedAt AuthType,Description,EndpointName,EndpointType,FunctionName,Regions,RevisionWeights,ScalingConfig,ThrottleConfig +AWS::Lambda::WebFunctionRevision CreatedAt,FunctionArn,RevisionArn,RevisionId,State,StateReason BuildConfig,Description,FunctionName,KmsKeyArn,ServiceConfig +AWS::Logs::LogGroup Arn BearerTokenAuthenticationEnabled,DataProtectionPolicy,DeletionProtectionEnabled,FieldIndexPolicies,KmsKeyId,LogGroupClass,LogGroupName,ResourcePolicyDocument,RetentionInDays,Tags +AWS::Logs::LogStream LogGroupName,LogStreamName +AWS::Logs::MetricFilter ApplyOnTransformedLogs,EmitSystemFieldDimensions,FieldSelectionCriteria,FilterName,FilterPattern,LogGroupName,MetricTransformations +AWS::Organizations::Account AccountId,Arn,JoinedMethod,JoinedTimestamp,Paths,State,Status AccountName,Email,ParentIds,RoleName,Tags +AWS::Organizations::Organization Arn,Id,ManagementAccountArn,ManagementAccountEmail,ManagementAccountId,RootId FeatureSet +AWS::Organizations::OrganizationalUnit Arn,Id,Path Name,ParentId,Tags +AWS::Organizations::Policy Arn,AwsManaged,Id Content,Description,Name,Tags,TargetIds,Type +AWS::Organizations::ResourcePolicy Arn,Id Content,Tags +AWS::Pipes::Pipe Arn,CreationTime,CurrentState,LastModifiedTime,StateReason Description,DesiredState,Enrichment,EnrichmentParameters,KmsKeyIdentifier,LogConfiguration,Name,RoleArn,Source,SourceParameters,Tags,Target,TargetParameters +AWS::RDS::DBCluster DBClusterArn,DBClusterResourceId,Endpoint,ReadEndpoint,StorageEncryptionType,StorageThroughput AllocatedStorage,AssociatedRoles,AutoMinorVersionUpgrade,AvailabilityZones,BacktrackWindow,BackupRetentionPeriod,ClusterScalabilityType,CopyTagsToSnapshot,DBClusterIdentifier,DBClusterInstanceClass,DBClusterParameterGroupName,DBInstanceParameterGroupName,DBSubnetGroupName,DBSystemId,DatabaseInsightsMode,DatabaseName,DeleteAutomatedBackups,DeletionProtection,Domain,DomainIAMRoleName,EnableCloudwatchLogsExports,EnableGlobalWriteForwarding,EnableHttpEndpoint,EnableIAMDatabaseAuthentication,EnableLocalWriteForwarding,Engine,EngineLifecycleSupport,EngineMode,EngineVersion,GlobalClusterIdentifier,Iops,KmsKeyId,ManageMasterUserPassword,MasterUserAuthenticationType,MasterUserPassword,MasterUserSecret,MasterUsername,MonitoringInterval,MonitoringRoleArn,NetworkType,PerformanceInsightsEnabled,PerformanceInsightsKmsKeyId,PerformanceInsightsRetentionPeriod,Port,PreferredBackupWindow,PreferredMaintenanceWindow,PubliclyAccessible,ReplicationSourceIdentifier,RestoreToTime,RestoreType,ScalingConfiguration,ServerlessV2ScalingConfiguration,SnapshotIdentifier,SourceDBClusterIdentifier,SourceDbClusterResourceId,SourceRegion,StorageEncrypted,StorageType,Tags,UseLatestRestorableTime,VpcSecurityGroupIds,WithExpressConfiguration +AWS::RDS::DBClusterParameterGroup DBClusterParameterGroupName,Description,Family,Parameters,Tags +AWS::RDS::DBInstance AutomaticRestartTime,CertificateDetails,DBInstanceArn,DBInstanceStatus,DbiResourceId,Endpoint,InstanceCreateTime,IsStorageConfigUpgradeAvailable,LatestRestorableTime,ListenerEndpoint,PercentProgress,ReadReplicaDBClusterIdentifiers,ReadReplicaDBInstanceIdentifiers,ResumeFullAutomationModeTime,SecondaryAvailabilityZone,StatusInfos,StorageOperationPercentProgress,StorageOperationStatus AdditionalStorageVolumes,AllocatedStorage,AllowMajorVersionUpgrade,ApplyImmediately,AssociatedRoles,AutoMinorVersionUpgrade,AutomaticBackupReplicationKmsKeyId,AutomaticBackupReplicationRegion,AutomaticBackupReplicationRetentionPeriod,AvailabilityZone,BackupRetentionPeriod,BackupTarget,CACertificateIdentifier,CertificateRotationRestart,CharacterSetName,CopyTagsToSnapshot,CustomIAMInstanceProfile,DBClusterIdentifier,DBClusterSnapshotIdentifier,DBInstanceClass,DBInstanceIdentifier,DBName,DBParameterGroupName,DBSecurityGroups,DBSnapshotIdentifier,DBSubnetGroupName,DBSystemId,DatabaseInsightsMode,DedicatedLogVolume,DeleteAutomatedBackups,DeletionProtection,Domain,DomainAuthSecretArn,DomainDnsIps,DomainFqdn,DomainIAMRoleName,DomainOu,EnableCloudwatchLogsExports,EnableIAMDatabaseAuthentication,EnablePerformanceInsights,Engine,EngineLifecycleSupport,EngineVersion,Iops,KmsKeyId,LicenseModel,ManageMasterUserPassword,MasterUserAuthenticationType,MasterUserPassword,MasterUserSecret,MasterUsername,MaxAllocatedStorage,MonitoringInterval,MonitoringRoleArn,MultiAZ,NcharCharacterSetName,NetworkType,OptionGroupName,PerformanceInsightsKMSKeyId,PerformanceInsightsRetentionPeriod,Port,PreferredBackupWindow,PreferredMaintenanceWindow,ProcessorFeatures,PromotionTier,PubliclyAccessible,ReplicaMode,RestoreTime,SourceDBClusterIdentifier,SourceDBInstanceAutomatedBackupsArn,SourceDBInstanceIdentifier,SourceDbiResourceId,SourceRegion,StorageEncrypted,StorageThroughput,StorageType,Tags,Timezone,UseDefaultProcessorFeatures,UseLatestRestorableTime,VPCSecurityGroups +AWS::RDS::DBParameterGroup DBParameterGroupArn DBParameterGroupName,Description,Family,Parameters,Tags +AWS::RDS::DBProxy DBProxyArn,Endpoint,VpcId Auth,DBProxyName,DebugLogging,DefaultAuthScheme,EndpointNetworkType,EngineFamily,IdleClientTimeout,RequireTLS,RoleArn,Tags,TargetConnectionNetworkType,VpcSecurityGroupIds,VpcSubnetIds +AWS::RDS::DBProxyTargetGroup TargetGroupArn ConnectionPoolConfigurationInfo,DBClusterIdentifiers,DBInstanceIdentifiers,DBProxyName,Tags,TargetGroupName +AWS::RDS::DBSubnetGroup DBSubnetGroupArn DBSubnetGroupDescription,DBSubnetGroupName,SubnetIds,Tags +AWS::Redshift::Cluster ClusterNamespaceArn,DeferMaintenanceIdentifier,MasterPasswordSecretArn AllowVersionUpgrade,AquaConfigurationStatus,AutomatedSnapshotRetentionPeriod,AvailabilityZone,AvailabilityZoneRelocation,AvailabilityZoneRelocationStatus,Classic,ClusterIdentifier,ClusterParameterGroupName,ClusterSecurityGroups,ClusterSubnetGroupName,ClusterType,ClusterVersion,DBName,DeferMaintenance,DeferMaintenanceDuration,DeferMaintenanceEndTime,DeferMaintenanceStartTime,DestinationRegion,ElasticIp,Encrypted,Endpoint,EnhancedVpcRouting,HsmClientCertificateIdentifier,HsmConfigurationIdentifier,IamRoles,KmsKeyId,LoggingProperties,MaintenanceTrackName,ManageMasterPassword,ManualSnapshotRetentionPeriod,MasterPasswordSecretKmsKeyId,MasterUserPassword,MasterUsername,MultiAZ,NamespaceResourcePolicy,NodeType,NumberOfNodes,OwnerAccount,Port,PreferredMaintenanceWindow,PubliclyAccessible,ResourceAction,RevisionTarget,RotateEncryptionKey,SnapshotClusterIdentifier,SnapshotCopyGrantName,SnapshotCopyManual,SnapshotCopyRetentionPeriod,SnapshotIdentifier,Tags,VpcSecurityGroupIds +AWS::Redshift::ClusterParameterGroup Description,ParameterGroupFamily,ParameterGroupName,Parameters,Tags +AWS::Redshift::ClusterSecurityGroup Id Description,Tags +AWS::Redshift::ClusterSubnetGroup ClusterSubnetGroupName Description,SubnetIds,Tags +AWS::Redshift::EventSubscription CustSubscriptionId,CustomerAwsId,EventCategoriesList,SourceIdsList,Status,SubscriptionCreationTime Enabled,EventCategories,Severity,SnsTopicArn,SourceIds,SourceType,SubscriptionName,Tags +AWS::RedshiftServerless::Namespace Namespace AdminPasswordSecretKmsKeyId,AdminUserPassword,AdminUsername,DbName,DefaultIamRoleArn,FinalSnapshotName,FinalSnapshotRetentionPeriod,IamRoles,KmsKeyId,LogExports,ManageAdminPassword,NamespaceName,NamespaceResourcePolicy,RedshiftIdcApplicationArn,SnapshotCopyConfigurations,Tags +AWS::RedshiftServerless::Workgroup BaseCapacity,ConfigParameters,EnhancedVpcRouting,MaxCapacity,NamespaceName,Port,PricePerformanceTarget,PubliclyAccessible,RecoveryPointId,SecurityGroupIds,SnapshotArn,SnapshotName,SnapshotOwnerAccount,SubnetIds,Tags,TrackName,Workgroup,WorkgroupName +AWS::Route53::HealthCheck HealthCheckId HealthCheckConfig,HealthCheckTags +AWS::Route53::HostedZone Id,NameServers DelegationSetId,HostedZoneConfig,HostedZoneFeatures,HostedZoneTags,Name,QueryLoggingConfig,VPCs +AWS::Route53::RecordSet AliasTarget,CidrRoutingConfig,Comment,Failover,GeoLocation,HealthCheckId,HostedZoneId,HostedZoneName,MultiValueAnswer,Name,Region,ResourceRecords,SetIdentifier,TTL,Type,Weight +AWS::Route53::RecordSetGroup Id Comment,HostedZoneId,HostedZoneName,RecordSets +AWS::S3::Bucket Arn,DomainName,DualStackDomainName,RegionalDomainName,WebsiteURL AbacStatus,AccelerateConfiguration,AccessControl,AnalyticsConfigurations,BucketEncryption,BucketName,BucketNamePrefix,BucketNamespace,CorsConfiguration,IntelligentTieringConfigurations,InventoryConfigurations,LifecycleConfiguration,LoggingConfiguration,MetadataConfiguration,MetadataTableConfiguration,MetricsConfigurations,NotificationConfiguration,ObjectLockConfiguration,ObjectLockEnabled,OwnershipControls,PublicAccessBlockConfiguration,ReplicationConfiguration,Tags,VersioningConfiguration,WebsiteConfiguration +AWS::S3::BucketPolicy Bucket,PolicyDocument +AWS::S3Vectors::Index CreationTime,IndexArn DataType,Dimension,DistanceMetric,EncryptionConfiguration,IndexName,MetadataConfiguration,Tags,VectorBucketArn,VectorBucketName +AWS::S3Vectors::VectorBucket CreationTime,VectorBucketArn EncryptionConfiguration,Tags,VectorBucketName +AWS::SES::EmailIdentity DkimDNSTokenName1,DkimDNSTokenName2,DkimDNSTokenName3,DkimDNSTokenValue1,DkimDNSTokenValue2,DkimDNSTokenValue3 ConfigurationSetAttributes,DkimAttributes,DkimSigningAttributes,EmailIdentity,FeedbackAttributes,MailFromAttributes,Tags +AWS::SES::ReceiptRule RuleName After,Rule,RuleSetName +AWS::SNS::Subscription Arn DeliveryPolicy,Endpoint,FilterPolicy,FilterPolicyScope,Protocol,RawMessageDelivery,RedrivePolicy,Region,ReplayPolicy,SubscriptionRoleArn,TopicArn +AWS::SNS::Topic TopicArn ArchivePolicy,ContentBasedDeduplication,DataProtectionPolicy,DeliveryStatusLogging,DisplayName,FifoThroughputScope,FifoTopic,KmsMasterKeyId,MaximumMessageSize,SignatureVersion,Subscription,Tags,TopicName,TracingConfig +AWS::SNS::TopicPolicy Id PolicyDocument,Topics +AWS::SQS::Queue Arn,QueueUrl ContentBasedDeduplication,DeduplicationScope,DelaySeconds,FifoQueue,FifoThroughputLimit,KmsDataKeyReusePeriodSeconds,KmsMasterKeyId,MaximumMessageSize,MessageRetentionPeriod,QueueName,ReceiveMessageWaitTimeSeconds,RedriveAllowPolicy,RedrivePolicy,SqsManagedSseEnabled,Tags,VisibilityTimeout +AWS::SQS::QueuePolicy Id PolicyDocument,Queues +AWS::SSM::Parameter Arn AllowedPattern,DataType,Description,Name,Policies,Tags,Tier,Type,Value +AWS::Scheduler::Schedule Arn Description,EndDate,FlexibleTimeWindow,GroupName,KmsKeyArn,Name,ScheduleExpression,ScheduleExpressionTimezone,StartDate,State,Target +AWS::Scheduler::ScheduleGroup Arn,CreationDate,LastModificationDate,State Name,Tags +AWS::SecretsManager::Secret Id Description,GenerateSecretString,KmsKeyId,Name,ReplicaRegions,SecretString,Tags,Type +AWS::SecretsManager::SecretTargetAttachment Id SecretId,TargetId,TargetType +AWS::ServiceDiscovery::HttpNamespace Arn,Id Description,Name,Tags +AWS::ServiceDiscovery::PrivateDnsNamespace Arn,HostedZoneId,Id Description,Name,Properties,Tags,Vpc +AWS::ServiceDiscovery::PublicDnsNamespace Arn,HostedZoneId,Id Description,Name,Properties,Tags +AWS::ServiceDiscovery::Service Arn,Id Description,DnsConfig,HealthCheckConfig,HealthCheckCustomConfig,Name,NamespaceId,ServiceAttributes,Tags,Type +AWS::StepFunctions::StateMachine Arn,Name,StateMachineRevisionId Definition,DefinitionS3Location,DefinitionString,DefinitionSubstitutions,EncryptionConfiguration,LoggingConfiguration,RoleArn,StateMachineName,StateMachineType,Tags,TracingConfiguration +AWS::Transfer::Server Arn,As2ServiceManagedEgressIpAddresses,ServerId,State Certificate,CreateWithHostKey,Domain,EndpointDetails,EndpointType,IdentityProviderDetails,IdentityProviderType,IpAddressType,LoggingRole,PostAuthenticationLoginBanner,PreAuthenticationLoginBanner,ProtocolDetails,Protocols,S3StorageOptions,SecurityPolicyName,StructuredLogDestinations,Tags,WorkflowDetails +AWS::Transfer::User Arn HomeDirectory,HomeDirectoryMappings,HomeDirectoryType,Policy,PosixProfile,Role,ServerId,SshPublicKeys,Tags,UserName +AWS::WAFv2::IPSet Arn,Id Addresses,Description,IPAddressVersion,Name,Scope,Tags +AWS::WAFv2::LoggingConfiguration ManagedByFirewallManager LogDestinationConfigs,LoggingFilter,RedactedFields,ResourceArn +AWS::WAFv2::WebACL Arn,Capacity,Id,LabelNamespace ApplicationConfig,AssociationConfig,CaptchaConfig,ChallengeConfig,CustomResponseBodies,DataProtectionConfig,DefaultAction,Description,MonetizationConfig,Name,OnSourceDDoSProtectionConfig,Rules,Scope,Tags,TokenDomains,VisibilityConfig +AWS::WAFv2::WebACLAssociation ResourceArn,WebACLArn diff --git a/tools/aws/regen_cfn_schema_surface.py b/tools/aws/regen_cfn_schema_surface.py new file mode 100644 index 0000000000..11575b4732 --- /dev/null +++ b/tools/aws/regen_cfn_schema_surface.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +"""Regenerate src/test/resources/cloudformation/schema-surface.tsv from CloudFormation's resource schemas. + +`CfnSchemaCoverageTest` compares what each supported resource type's registry schema declares with +what its provisioner sets and reads. It used to read the schemas from a gitignored `local/` checkout, +so the comparison ran only on a machine that had one. This file is the part of the schemas the +comparison uses, committed, so it runs on every pull request. One row per resource type in +`supported-resource-types.tsv`: + + + +Read-only attributes are the top-level `readOnlyProperties` pointers, which are the `Fn::GetAtt` +names. Writable properties are the top-level `properties` keys that are neither read-only nor +deprecated; write-only ones are writable. Nested members are out. Names are sorted. A type with no +schema in the archive has no row, and the test accepts that only for the types it declares schema-less. + +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_schema_surface.py # fetch and rewrite the committed file + python3 tools/aws/regen_cfn_schema_surface.py --verify # online: the committed file matches AWS + python3 tools/aws/regen_cfn_schema_surface.py --source-dir

-.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 + +REPO_ROOT = Path(__file__).resolve().parents[2] +OUTPUT = REPO_ROOT / "src/test/resources/cloudformation/schema-surface.tsv" +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 +# Inventory types that have no schema in the archive; the same set as TYPES_WITHOUT_SCHEMA in +# CfnSchemaCoverageTest. Any other type without a schema fails the run by name. +SCHEMALESS = frozenset({"AWS::CDK::Metadata", "Custom::DynamoDBReplica"}) + + +def file_name(resource_type: str) -> str: + """The archive's file for a resource type: AWS::Events::Rule is aws-events-rule.json.""" + return resource_type.lower().replace("::", "-") + ".json" + + +def inventory_types(inventory: Path) -> list[str]: + return sorted(line.split("\t", 1)[0] for line in inventory.read_text(encoding="utf-8").splitlines() + if line.strip()) + + +def top_level_names(pointers: list[str]) -> set[str]: + """The name of each `/properties/` pointer; a nested pointer is not a top-level property.""" + names = set() + for pointer in pointers: + if not isinstance(pointer, str): + raise ValueError(f"expected a pointer string, found {pointer!r}") + parts = pointer.split("/") + # "/properties/Name" only: a trailing slash or a nested pointer is not a top-level name. + if len(parts) == 3 and parts[0] == "" and parts[1] == "properties" and parts[2] != "": + names.add(parts[2]) + return names + + +def surface(schema: dict) -> tuple[list[str], list[str]]: + """The read-only attributes and the writable properties of one schema, each sorted.""" + properties = schema.get("properties", {}) + if not isinstance(properties, dict): + raise ValueError("'properties' is not an object") + for key in ("readOnlyProperties", "deprecatedProperties"): + if not isinstance(schema.get(key, []), list): + raise ValueError(f"'{key}' is not a list") + read_only = top_level_names(schema.get("readOnlyProperties", [])) + excluded = read_only | top_level_names(schema.get("deprecatedProperties", [])) + writable = {name for name in properties if name not in excluded} + return sorted(read_only), sorted(writable) + + +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: + rows = [] + for resource_type in sorted(schemas): + read_only, writable = surface(schemas[resource_type]) + rows.append(f"{resource_type}\t{','.join(read_only)}\t{','.join(writable)}\n") + return "".join(rows) + + +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 committed file matches AWS's schemas") + parser.add_argument("--source-dir", type=Path, default=None, + help="read saved aws--.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: + 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-schema-surface-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()) diff --git a/tools/aws/test_regen_cfn_schema_surface.py b/tools/aws/test_regen_cfn_schema_surface.py new file mode 100644 index 0000000000..7a4a38f459 --- /dev/null +++ b/tools/aws/test_regen_cfn_schema_surface.py @@ -0,0 +1,125 @@ +"""Tests for regen_cfn_schema_surface. + +Run with: pytest tools/aws -q (or: make aws-data-test) +""" +from __future__ import annotations + +import json + +import pytest + +import regen_cfn_schema_surface as r + +SCHEMA = { + "typeName": "AWS::Test::Thing", + "properties": { + "Arn": {"type": "string"}, + "Name": {"type": "string"}, + "Old": {"type": "string"}, + "Secret": {"type": "string"}, + "Nested": {"type": "object", "properties": {"Id": {"type": "string"}}}, + }, + "readOnlyProperties": ["/properties/Arn", "/properties/Nested/Id"], + "deprecatedProperties": ["/properties/Old"], + "writeOnlyProperties": ["/properties/Secret"], +} + + +def test_surface_splits_attributes_from_properties(): + read_only, writable = r.surface(SCHEMA) + assert read_only == ["Arn"] + assert writable == ["Name", "Nested", "Secret"] + + +def test_nested_pointers_are_not_top_level_names(): + assert r.top_level_names(["/properties/A", "/properties/B/C", "/properties/D/"]) == {"A"} + + +def test_file_name_follows_the_archive(): + assert r.file_name("AWS::Events::Rule") == "aws-events-rule.json" + + +def test_render_has_one_row_per_type_and_empty_columns_stay_columns(): + schemas = {"AWS::Test::Thing": SCHEMA, "AWS::Test::Bare": {"properties": {"Id": {}}}} + assert r.render(schemas) == ( + "AWS::Test::Bare\t\tId\n" + "AWS::Test::Thing\tArn\tName,Nested,Secret\n") + + +def test_sync_then_verify_from_a_saved_directory(tmp_path, monkeypatch): + monkeypatch.setattr(r, "SCHEMALESS", frozenset({"Custom::NoSchema"})) + source = tmp_path / "schemas" + source.mkdir() + (source / "aws-test-thing.json").write_text(json.dumps(SCHEMA), encoding="utf-8") + inventory = tmp_path / "inventory.tsv" + inventory.write_text("AWS::Test::Thing\tThingProvisioner\nCustom::NoSchema\tOther\n", encoding="utf-8") + output = tmp_path / "surface.tsv" + args = ["--source-dir", str(source), "--inventory", str(inventory), "--output", str(output)] + + assert r.main(args) == 0 + assert output.read_text(encoding="utf-8") == "AWS::Test::Thing\tArn\tName,Nested,Secret\n" + assert r.main(args + ["--verify"]) == 0 + + output.write_text("AWS::Test::Thing\tArn\tName\n", encoding="utf-8") + assert r.main(args + ["--verify"]) == 1 + + +def test_a_trailing_slash_pointer_is_not_top_level(): + # The Java code this replaced split the pointer without stripping, so /properties/C/ had four parts. + assert r.top_level_names(["/properties/A", "/properties/C/"]) == {"A"} + + +def _setup(tmp_path, schemas): + source = tmp_path / "schemas" + source.mkdir() + for name, content in schemas.items(): + (source / name).write_text(content, encoding="utf-8") + inventory = tmp_path / "inventory.tsv" + inventory.write_text("AWS::Test::Thing\tP\nAWS::Test::Other\tP\nCustom::NoSchema\tP\n", encoding="utf-8") + output = tmp_path / "surface.tsv" + args = ["--source-dir", str(source), "--inventory", str(inventory), "--output", str(output)] + return args, output + + +def test_a_missing_schema_fails_by_name_and_writes_nothing(tmp_path, capsys, monkeypatch): + monkeypatch.setattr(r, "SCHEMALESS", frozenset({"Custom::NoSchema"})) + args, output = _setup(tmp_path, {"aws-test-thing.json": json.dumps(SCHEMA)}) + assert r.main(args) == 1 + assert "AWS::Test::Other" in capsys.readouterr().err + assert not output.exists() + assert r.main(args + ["--verify"]) == 1 + + +def test_an_empty_source_dir_fails_and_writes_nothing(tmp_path, monkeypatch): + monkeypatch.setattr(r, "SCHEMALESS", frozenset({"Custom::NoSchema"})) + args, output = _setup(tmp_path, {}) + assert r.main(args) == 1 + assert not output.exists() + + +@pytest.mark.parametrize("schema", [ + {"properties": {"A": {}}, "readOnlyProperties": [1]}, + {"properties": {"A": {}}, "readOnlyProperties": [None]}, + {"properties": {"A": {}}, "deprecatedProperties": [["x"]]}, + {"properties": ["A"]}, + {"properties": {"A": {}}, "readOnlyProperties": "/properties/A"}, +]) +def test_a_malformed_schema_is_a_read_failure_not_a_difference(tmp_path, monkeypatch, schema): + monkeypatch.setattr(r, "SCHEMALESS", frozenset({"Custom::NoSchema"})) + both = {"aws-test-thing.json": json.dumps(schema), "aws-test-other.json": json.dumps(SCHEMA)} + args, output = _setup(tmp_path, both) + assert r.main(args) == 2 + assert r.main(args + ["--verify"]) == 2 + assert not output.exists() + + +def test_an_incomplete_read_is_a_read_failure(tmp_path, monkeypatch, capsys): + import http.client + + def broken(*_args): + raise http.client.IncompleteRead(b"partial") + + monkeypatch.setattr(r, "fetch_schemas", broken) + args, _ = _setup(tmp_path, {}) + assert r.main(args[2:]) == 2 + assert "could not read" in capsys.readouterr().err