ruby-cdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +87 -0
  3. data/LICENSE +21 -0
  4. data/README.md +303 -0
  5. data/THIRD_PARTY_NOTICES.md +327 -0
  6. data/data/spec/META.json +33 -0
  7. data/data/spec/model.json.gz +0 -0
  8. data/exe/ruby-cdk +9 -0
  9. data/lib/ruby-cdk.rb +4 -0
  10. data/lib/ruby_cdk/assets/builder.rb +122 -0
  11. data/lib/ruby_cdk/assets/hasher.rb +175 -0
  12. data/lib/ruby_cdk/assets/record.rb +49 -0
  13. data/lib/ruby_cdk/assets/uploader.rb +139 -0
  14. data/lib/ruby_cdk/assets/zipper.rb +108 -0
  15. data/lib/ruby_cdk/assets.rb +116 -0
  16. data/lib/ruby_cdk/bootstrap.rb +289 -0
  17. data/lib/ruby_cdk/cfn/resource.rb +93 -0
  18. data/lib/ruby_cdk/cfn.rb +10 -0
  19. data/lib/ruby_cdk/cli/arguments.rb +41 -0
  20. data/lib/ruby_cdk/cli/aws.rb +35 -0
  21. data/lib/ruby_cdk/cli/bootstrap.rb +63 -0
  22. data/lib/ruby_cdk/cli/diff.rb +98 -0
  23. data/lib/ruby_cdk/cli/failure.rb +80 -0
  24. data/lib/ruby_cdk/cli/io.rb +70 -0
  25. data/lib/ruby_cdk/cli/list.rb +46 -0
  26. data/lib/ruby_cdk/cli/new.rb +313 -0
  27. data/lib/ruby_cdk/cli/operation.rb +124 -0
  28. data/lib/ruby_cdk/cli/pairs.rb +32 -0
  29. data/lib/ruby_cdk/cli/report.rb +118 -0
  30. data/lib/ruby_cdk/cli/selection.rb +134 -0
  31. data/lib/ruby_cdk/cli/session.rb +290 -0
  32. data/lib/ruby_cdk/cli/shell.rb +30 -0
  33. data/lib/ruby_cdk/cli/synth.rb +58 -0
  34. data/lib/ruby_cdk/cli/validate.rb +101 -0
  35. data/lib/ruby_cdk/cli.rb +242 -0
  36. data/lib/ruby_cdk/constructs/bucket.rb +191 -0
  37. data/lib/ruby_cdk/constructs/function.rb +163 -0
  38. data/lib/ruby_cdk/constructs/grant.rb +90 -0
  39. data/lib/ruby_cdk/constructs/log_group.rb +115 -0
  40. data/lib/ruby_cdk/constructs/policy_statement.rb +161 -0
  41. data/lib/ruby_cdk/constructs/queue.rb +118 -0
  42. data/lib/ruby_cdk/constructs/role.rb +282 -0
  43. data/lib/ruby_cdk/constructs/table.rb +160 -0
  44. data/lib/ruby_cdk/constructs/topic.rb +88 -0
  45. data/lib/ruby_cdk/constructs.rb +56 -0
  46. data/lib/ruby_cdk/core/app.rb +146 -0
  47. data/lib/ruby_cdk/core/construct.rb +105 -0
  48. data/lib/ruby_cdk/core/elements.rb +107 -0
  49. data/lib/ruby_cdk/core/ids.rb +117 -0
  50. data/lib/ruby_cdk/core/stack.rb +291 -0
  51. data/lib/ruby_cdk/core/stateful.rb +156 -0
  52. data/lib/ruby_cdk/core.rb +15 -0
  53. data/lib/ruby_cdk/deploy/capabilities.rb +44 -0
  54. data/lib/ruby_cdk/deploy/deployer.rb +805 -0
  55. data/lib/ruby_cdk/deploy/errors.rb +72 -0
  56. data/lib/ruby_cdk/deploy/fakes.rb +546 -0
  57. data/lib/ruby_cdk/deploy/output/base.rb +167 -0
  58. data/lib/ruby_cdk/deploy/output/human.rb +37 -0
  59. data/lib/ruby_cdk/deploy/output/json.rb +80 -0
  60. data/lib/ruby_cdk/deploy/output/quiet.rb +20 -0
  61. data/lib/ruby_cdk/deploy/parameters.rb +86 -0
  62. data/lib/ruby_cdk/deploy/poller.rb +72 -0
  63. data/lib/ruby_cdk/deploy/ports.rb +205 -0
  64. data/lib/ruby_cdk/deploy/sdk_adapters.rb +608 -0
  65. data/lib/ruby_cdk/deploy/states.rb +62 -0
  66. data/lib/ruby_cdk/deploy.rb +25 -0
  67. data/lib/ruby_cdk/diff/compare.rb +141 -0
  68. data/lib/ruby_cdk/diff/normalizer.rb +83 -0
  69. data/lib/ruby_cdk/diff/render.rb +242 -0
  70. data/lib/ruby_cdk/diff/security.rb +322 -0
  71. data/lib/ruby_cdk/diff/statement.rb +256 -0
  72. data/lib/ruby_cdk/diff/template.rb +524 -0
  73. data/lib/ruby_cdk/diff.rb +62 -0
  74. data/lib/ruby_cdk/env.rb +42 -0
  75. data/lib/ruby_cdk/errors.rb +38 -0
  76. data/lib/ruby_cdk/fn.rb +409 -0
  77. data/lib/ruby_cdk/lazy.rb +55 -0
  78. data/lib/ruby_cdk/nag/config.rb +303 -0
  79. data/lib/ruby_cdk/nag/engine.rb +152 -0
  80. data/lib/ruby_cdk/nag/report.rb +86 -0
  81. data/lib/ruby_cdk/nag/rule.rb +171 -0
  82. data/lib/ruby_cdk/nag/rules/api_gateway_authorization.rb +91 -0
  83. data/lib/ruby_cdk/nag/rules/dynamodb_point_in_time_recovery.rb +45 -0
  84. data/lib/ruby_cdk/nag/rules/ebs_volume_encrypted.rb +41 -0
  85. data/lib/ruby_cdk/nag/rules/ec2_ingress_http.rb +48 -0
  86. data/lib/ruby_cdk/nag/rules/ec2_ingress_other_ports.rb +46 -0
  87. data/lib/ruby_cdk/nag/rules/iam_policy_admin_access.rb +60 -0
  88. data/lib/ruby_cdk/nag/rules/iam_policy_full_access.rb +55 -0
  89. data/lib/ruby_cdk/nag/rules/iam_user_credentials.rb +61 -0
  90. data/lib/ruby_cdk/nag/rules/lambda_runtime_supported.rb +88 -0
  91. data/lib/ruby_cdk/nag/rules/lambda_secret_environment.rb +61 -0
  92. data/lib/ruby_cdk/nag/rules/log_group_retention.rb +40 -0
  93. data/lib/ruby_cdk/nag/rules/policy_statements.rb +128 -0
  94. data/lib/ruby_cdk/nag/rules/rds_storage_encrypted.rb +65 -0
  95. data/lib/ruby_cdk/nag/rules/resource_policy_wildcard_principal.rb +58 -0
  96. data/lib/ruby_cdk/nag/rules/s3_public_access_block.rb +56 -0
  97. data/lib/ruby_cdk/nag/rules/security_group_ingress.rb +136 -0
  98. data/lib/ruby_cdk/nag/rules/stateful_deletion_policy.rb +46 -0
  99. data/lib/ruby_cdk/nag/rules.rb +51 -0
  100. data/lib/ruby_cdk/nag/values.rb +305 -0
  101. data/lib/ruby_cdk/nag.rb +60 -0
  102. data/lib/ruby_cdk/schema/normalizer.rb +164 -0
  103. data/lib/ruby_cdk/schema/property_schema.rb +22 -0
  104. data/lib/ruby_cdk/schema/schema.rb +195 -0
  105. data/lib/ruby_cdk/schema/sources/compiler.rb +56 -0
  106. data/lib/ruby_cdk/schema/sources/descriptor.rb +21 -0
  107. data/lib/ruby_cdk/schema/sources/download.rb +86 -0
  108. data/lib/ruby_cdk/schema/sources/provider_schemas.rb +47 -0
  109. data/lib/ruby_cdk/schema/sources/provider_type.rb +630 -0
  110. data/lib/ruby_cdk/schema/sources/regions.rb +86 -0
  111. data/lib/ruby_cdk/schema/sources/resource_specification.rb +94 -0
  112. data/lib/ruby_cdk/schema/sources/specification_type.rb +159 -0
  113. data/lib/ruby_cdk/schema/sources/update.rb +178 -0
  114. data/lib/ruby_cdk/schema/sources.rb +20 -0
  115. data/lib/ruby_cdk/schema/type_schema.rb +109 -0
  116. data/lib/ruby_cdk/schema/validator/corpus_check.rb +81 -0
  117. data/lib/ruby_cdk/schema/validator/policies.rb +48 -0
  118. data/lib/ruby_cdk/schema/validator/refs.rb +489 -0
  119. data/lib/ruby_cdk/schema/validator/report.rb +92 -0
  120. data/lib/ruby_cdk/schema/validator/rule.rb +119 -0
  121. data/lib/ruby_cdk/schema/validator/scans.rb +146 -0
  122. data/lib/ruby_cdk/schema/validator/structure.rb +469 -0
  123. data/lib/ruby_cdk/schema/validator/template.rb +203 -0
  124. data/lib/ruby_cdk/schema/validator/template_rules.rb +70 -0
  125. data/lib/ruby_cdk/schema/validator/walk.rb +122 -0
  126. data/lib/ruby_cdk/schema/validator.rb +159 -0
  127. data/lib/ruby_cdk/schema.rb +19 -0
  128. data/lib/ruby_cdk/synth/manifest.rb +128 -0
  129. data/lib/ruby_cdk/synth/resolver.rb +326 -0
  130. data/lib/ruby_cdk/synth/rules.rb +83 -0
  131. data/lib/ruby_cdk/synth/serializer.rb +120 -0
  132. data/lib/ruby_cdk/synth/writer.rb +31 -0
  133. data/lib/ruby_cdk/synth.rb +255 -0
  134. data/lib/ruby_cdk/test/capture.rb +133 -0
  135. data/lib/ruby_cdk/test/match.rb +426 -0
  136. data/lib/ruby_cdk/test/matcher.rb +290 -0
  137. data/lib/ruby_cdk/test/private/absent.rb +34 -0
  138. data/lib/ruby_cdk/test/private/conditions.rb +39 -0
  139. data/lib/ruby_cdk/test/private/cyclic.rb +160 -0
  140. data/lib/ruby_cdk/test/private/error.rb +48 -0
  141. data/lib/ruby_cdk/test/private/js.rb +326 -0
  142. data/lib/ruby_cdk/test/private/mappings.rb +39 -0
  143. data/lib/ruby_cdk/test/private/outputs.rb +39 -0
  144. data/lib/ruby_cdk/test/private/parameters.rb +39 -0
  145. data/lib/ruby_cdk/test/private/resources.rb +116 -0
  146. data/lib/ruby_cdk/test/private/section.rb +98 -0
  147. data/lib/ruby_cdk/test/private/sorting.rb +40 -0
  148. data/lib/ruby_cdk/test/private/sparse_matrix.rb +35 -0
  149. data/lib/ruby_cdk/test/private/type.rb +23 -0
  150. data/lib/ruby_cdk/test/template.rb +364 -0
  151. data/lib/ruby_cdk/test.rb +116 -0
  152. data/lib/ruby_cdk/values.rb +8 -0
  153. data/lib/ruby_cdk/version.rb +5 -0
  154. data/lib/ruby_cdk.rb +47 -0
  155. metadata +256 -0
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../../errors"
4
+
5
+ module RubyCdk
6
+ module Schema
7
+ module Sources
8
+ # Where each region publishes the two sources.
9
+ module Regions
10
+ # Raised for a region that is not in the table.
11
+ class Unknown < RubyCdk::Error; end
12
+
13
+ # The provider schemas follow one pattern in every region.
14
+ PROVIDER_URL = "https://schema.cloudformation.%<region>s.amazonaws.com/CloudformationSchema.zip"
15
+
16
+ # The resource specification has one address per region, with no pattern to derive it
17
+ # from. Read in full from "CloudFormation resource specification",
18
+ # https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/cfn-resource-specification.html,
19
+ # on 2026-11-24, after the older revision this table was first written from had gone
20
+ # stale: sixteen addresses had moved (eight no longer resolved, the Mexico bucket
21
+ # gained an account ID, the GovCloud buckets moved off path-style addressing, and
22
+ # ten more now sit behind CloudFront), and the page had grown four regions.
23
+ #
24
+ # The previous revision of this page had been the source of eleven dead addresses,
25
+ # which is why the whole table is rewritten from the page rather than patched.
26
+ #
27
+ # Jakarta, Melbourne, Malaysia, Thailand, Canada West and both GovCloud regions serve
28
+ # the file uncompressed: their addresses carry no /gzip/ segment. The parser reads
29
+ # either form. The two China regions are on the page but their endpoints did not
30
+ # answer from where this table was written (the connection failed; AWS serves them
31
+ # from within China only); they are kept because the page is the reference and a
32
+ # build there will work or fail loudly with a 404. The other twenty-five addresses
33
+ # in the table answered HTTP 200 on 2026-11-24.
34
+ SPECIFICATION_URLS = {
35
+ "us-east-2" => "https://dnwj8swjjbsbt.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json",
36
+ "us-east-1" => "https://d1uauaxba7bl26.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json",
37
+ "us-west-1" => "https://d68hl49wbnanq.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json",
38
+ "us-west-2" => "https://d201a2mn26r7lk.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json",
39
+ "af-south-1" => "https://cfn-resource-specifications-af-south-1-prod.s3.af-south-1.amazonaws.com/latest/gzip/CloudFormationResourceSpecification.json",
40
+ "ap-east-1" => "https://cfn-resource-specifications-ap-east-1-prod.s3.ap-east-1.amazonaws.com/latest/gzip/CloudFormationResourceSpecification.json",
41
+ "ap-south-2" => "https://cfn-resource-specifications-ap-south-2-prod.s3.ap-south-2.amazonaws.com/latest/gzip/CloudFormationResourceSpecification.json",
42
+ "ap-southeast-3" => "https://cfn-resource-specifications-ap-southeast-3-prod.s3.ap-southeast-3.amazonaws.com/latest/CloudFormationResourceSpecification.json",
43
+ "ap-southeast-4" => "https://cfn-resource-specifications-ap-southeast-4-prod.s3.ap-southeast-4.amazonaws.com/latest/CloudFormationResourceSpecification.json",
44
+ "ap-southeast-5" => "https://cfn-resource-specifications-ap-southeast-5-prod.s3.ap-southeast-5.amazonaws.com/latest/CloudFormationResourceSpecification.json",
45
+ "ap-east-2" => "https://cfn-resource-specifications-ap-east-2-975050364454-prod.s3.ap-east-2.amazonaws.com/latest/gzip/CloudFormationResourceSpecification.json",
46
+ "ap-southeast-7" => "https://cfn-resource-specifications-ap-southeast-7-767397843873-prod.s3.ap-southeast-7.amazonaws.com/latest/CloudFormationResourceSpecification.json",
47
+ "ap-south-1" => "https://d2senuesg1djtx.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json",
48
+ "ap-northeast-3" => "https://d2zq80gdmjim8k.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json",
49
+ "ap-northeast-2" => "https://d1ane3fvebulky.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json",
50
+ "ap-southeast-1" => "https://doigdx0kgq9el.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json",
51
+ "ap-southeast-2" => "https://d2stg8d246z9di.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json",
52
+ "ap-northeast-1" => "https://d33vqc0rt9ld30.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json",
53
+ "ca-central-1" => "https://d2s8ygphhesbe7.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json",
54
+ "ca-west-1" => "https://cfn-resource-specifications-ca-west-1-prod.s3.ca-west-1.amazonaws.com/latest/CloudFormationResourceSpecification.json",
55
+ "cn-north-1" => "https://cfn-resource-specifications-cn-north-1-prod.s3.cn-north-1.amazonaws.com.cn/latest/gzip/CloudFormationResourceSpecification.json",
56
+ "cn-northwest-1" => "https://cfn-resource-specifications-cn-northwest-1-prod.s3.cn-northwest-1.amazonaws.com.cn/latest/gzip/CloudFormationResourceSpecification.json",
57
+ "eu-central-1" => "https://d1mta8qj7i28i2.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json",
58
+ "eu-west-1" => "https://d3teyb21fexa9r.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json",
59
+ "eu-west-2" => "https://d1742qcu2c1ncx.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json",
60
+ "eu-south-1" => "https://cfn-resource-specifications-eu-south-1-prod.s3.eu-south-1.amazonaws.com/latest/gzip/CloudFormationResourceSpecification.json",
61
+ "eu-west-3" => "https://d2d0mfegowb3wk.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json",
62
+ "eu-south-2" => "https://cfn-resource-specifications-eu-south-2-prod.s3.eu-south-2.amazonaws.com/latest/gzip/CloudFormationResourceSpecification.json",
63
+ "eu-north-1" => "https://diy8iv58sj6ba.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json",
64
+ "eu-central-2" => "https://cfn-resource-specifications-eu-central-2-prod.s3.eu-central-2.amazonaws.com/latest/gzip/CloudFormationResourceSpecification.json",
65
+ "il-central-1" => "https://cfn-resource-specifications-il-central-1-prod.s3.il-central-1.amazonaws.com/latest/gzip/CloudFormationResourceSpecification.json",
66
+ "me-south-1" => "https://cfn-resource-specifications-me-south-1-prod.s3.me-south-1.amazonaws.com/latest/gzip/CloudFormationResourceSpecification.json",
67
+ "me-central-1" => "https://cfn-resource-specifications-me-central-1-prod.s3.me-central-1.amazonaws.com/latest/gzip/CloudFormationResourceSpecification.json",
68
+ "mx-central-1" => "https://cfn-resource-specifications-mx-central-1-590183656522-prod.s3.mx-central-1.amazonaws.com/latest/gzip/CloudFormationResourceSpecification.json",
69
+ "sa-east-1" => "https://d3c9jyj3w509b0.cloudfront.net/latest/gzip/CloudFormationResourceSpecification.json",
70
+ "us-gov-east-1" => "https://s3.us-gov-east-1.amazonaws.com/cfn-resource-specifications-us-gov-east-1-prod/latest/CloudFormationResourceSpecification.json",
71
+ "us-gov-west-1" => "https://s3.us-gov-west-1.amazonaws.com/cfn-resource-specifications-us-gov-west-1-prod/latest/CloudFormationResourceSpecification.json"
72
+ }.freeze
73
+
74
+ class << self
75
+ # { provider_schemas: url, resource_specification: url } for one region.
76
+ def urls(region)
77
+ specification = SPECIFICATION_URLS[region] or
78
+ raise Unknown, "#{region.inspect} is not in the specification table (lib/ruby_cdk/schema/sources/regions.rb). " \
79
+ "Add its address from the AWS CloudFormation resource specification reference, or build one of: #{SPECIFICATION_URLS.keys.join(", ")}"
80
+ { provider_schemas: format(PROVIDER_URL, region:), resource_specification: specification }
81
+ end
82
+ end
83
+ end
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "zlib"
5
+ require_relative "../../errors"
6
+
7
+ module RubyCdk
8
+ module Schema
9
+ module Sources
10
+ # The resource specification of one region, parsed, with the lookups the compilers need.
11
+ #
12
+ # Its shape: ResourceTypes and PropertyTypes, and ResourceSpecificationVersion. A
13
+ # property is a primitive (PrimitiveType), a list or a map (Type List or Map, with
14
+ # PrimitiveItemType or ItemType), or a nested property type (Type, named relative to
15
+ # the resource type: "Code" on AWS::Lambda::Function is AWS::Lambda::Function.Code).
16
+ # Tag is the one name every resource type shares.
17
+ class ResourceSpecification
18
+ CONTAINERS = %w[List Map].freeze
19
+ TOP_LEVEL = %w[PropertyTypes ResourceTypes ResourceSpecificationVersion].freeze
20
+
21
+ # How many list or map property types may sit on top of each other before the
22
+ # lookup gives up: a guard against a specification that refers to itself.
23
+ MAX_INDIRECTIONS = 10
24
+
25
+ class << self
26
+ # bytes: the gzip as published. Plain JSON is read as well.
27
+ def parse(bytes)
28
+ document = JSON.parse(inflate(bytes))
29
+ raise RubyCdk::Error, "the resource specification is not one JSON object" unless document.is_a?(Hash)
30
+
31
+ missing = TOP_LEVEL - document.keys
32
+ raise RubyCdk::Error, "the resource specification lacks #{missing.join(", ")}" if missing.any?
33
+
34
+ new(document)
35
+ rescue JSON::ParserError
36
+ raise RubyCdk::Error, "the resource specification is not JSON"
37
+ end
38
+
39
+ private
40
+
41
+ def inflate(bytes)
42
+ Zlib.gunzip(bytes)
43
+ rescue Zlib::GzipFile::Error
44
+ bytes
45
+ end
46
+ end
47
+
48
+ attr_reader :version
49
+
50
+ def initialize(document)
51
+ @resource_types = document.fetch("ResourceTypes")
52
+ @property_types = document.fetch("PropertyTypes")
53
+ @version = document.fetch("ResourceSpecificationVersion")
54
+ end
55
+
56
+ # { "AWS::Lambda::Function" => { "Documentation" => ..., "Properties" => ..., "Attributes" => ... }, ... }
57
+ def resource_types
58
+ @resource_types
59
+ end
60
+
61
+ def resource_type(name)
62
+ @resource_types[name]
63
+ end
64
+
65
+ # The property type `name` of a resource type: "AWS::Lambda::Function.Code", or the shared Tag.
66
+ def property_type(resource_type, name)
67
+ @property_types["#{resource_type}.#{name}"] || @property_types[name]
68
+ end
69
+
70
+ # The properties of what `property` holds, when the specification describes them
71
+ # with named properties: of its nested type, of its list's elements or of its map's
72
+ # values. nil for a primitive, a list or a map of primitives, or a name it does not know.
73
+ def properties(resource_type, property)
74
+ name = property["ItemType"] || (property["Type"] unless CONTAINERS.include?(property["Type"]))
75
+ return nil unless name.is_a?(String)
76
+
77
+ held_by(resource_type, property_type(resource_type, name))
78
+ end
79
+
80
+ private
81
+
82
+ # The named properties of a property type. One that is itself a list or a map
83
+ # ("AWS::LakeFormation::DataLakeSettings.Admins") is followed to what it holds.
84
+ def held_by(resource_type, type, depth = 0)
85
+ return nil unless type.is_a?(Hash) && depth < MAX_INDIRECTIONS
86
+ return type["Properties"] unless CONTAINERS.include?(type["Type"])
87
+
88
+ item = type["ItemType"]
89
+ item.is_a?(String) ? held_by(resource_type, property_type(resource_type, item), depth + 1) : nil
90
+ end
91
+ end
92
+ end
93
+ end
94
+ end
@@ -0,0 +1,159 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../../errors"
4
+
5
+ module RubyCdk
6
+ module Schema
7
+ module Sources
8
+ # Compiles a resource type the resource specification describes, and the odd property
9
+ # of a provider-backed type that only the specification knows.
10
+ #
11
+ # This is how a specification property becomes a kind:
12
+ #
13
+ # PrimitiveType String, Boolean, Integer, Double, Long
14
+ # :string, :boolean, :integer, :double, :long
15
+ # PrimitiveType Json :json
16
+ # PrimitiveType Timestamp :timestamp
17
+ # Type List, Type Map :list or :map; the element from PrimitiveItemType, or
18
+ # from ItemType, which names a nested property type
19
+ # Type <name> :nested, a definition under that name
20
+ #
21
+ # A property type that is itself a list or a map ("AWS::LakeFormation::DataLakeSettings.Admins")
22
+ # is followed to its element. A name the specification does not define is :json.
23
+ # The specification has no allowed values and no patterns. It does publish
24
+ # timestamps: the Timestamp primitive, twice in version 273.0.0.
25
+ class SpecificationType
26
+ PRIMITIVES = { "String" => :string, "Boolean" => :boolean, "Integer" => :integer, "Json" => :json, "Double" => :double, "Long" => :long, "Timestamp" => :timestamp }.freeze
27
+ CONTAINERS = %w[List Map].freeze
28
+ UPDATES = { "Mutable" => "mutable", "Immutable" => "immutable", "Conditional" => "conditional" }.freeze
29
+
30
+ # What the specification adds to a type the provider schema also describes:
31
+ # entries are [name, entry] pairs, definitions the nested types they reach.
32
+ Extra = Data.define(:entries, :definitions)
33
+
34
+ def initialize(specification, type_name)
35
+ @specification = specification
36
+ @type_name = type_name
37
+ @definitions = {}
38
+ @queue = []
39
+ end
40
+
41
+ # For properties only the specification knows: { "Name" => property, ... }.
42
+ def extra(properties)
43
+ entries = properties.map { |name, property| [ name, entry(property) ] }
44
+ drain
45
+ Extra.new(entries:, definitions: @definitions)
46
+ end
47
+
48
+ # The type as the model stores it.
49
+ def call
50
+ resource = @specification.resource_type(@type_name) or
51
+ raise RubyCdk::Error, "the resource specification does not describe #{@type_name}"
52
+ properties = resource["Properties"] || {}
53
+ entries = properties.map { |name, property| [ name, entry(property) ] }
54
+ drain
55
+
56
+ type = {
57
+ "source" => "specification",
58
+ "documentation_url" => resource["Documentation"]&.sub(%r{\Ahttp://docs\.aws\.amazon\.com/}, "https://docs.aws.amazon.com/"),
59
+ "required" => properties.select { |_, property| property["Required"] }.keys.sort,
60
+ "create_only" => properties.filter_map { |name, property| name if property["UpdateType"] == "Immutable" }.sort,
61
+ "read_only" => resource["Attributes"].is_a?(Hash) ? resource["Attributes"].keys.sort : [],
62
+ "properties" => entries,
63
+ "definitions" => @definitions
64
+ }
65
+ # AWS::CloudFormation::CustomResource: a template may set any property.
66
+ type["additional_properties"] = true if resource["AdditionalProperties"] == true
67
+ type
68
+ end
69
+
70
+ private
71
+
72
+ # A property's entry. Every property reaches drain with the nested types it names queued.
73
+ def entry(property)
74
+ kind, item, of, unique = describe(property)
75
+ entry = { "kind" => kind.to_s }
76
+ entry["item"] = item.to_s if item
77
+ entry["of"] = of if of
78
+ entry["update"] = UPDATES.fetch(property["UpdateType"]) do
79
+ raise RubyCdk::Error, "#{@type_name}: the specification gives a property the update type #{property["UpdateType"].inspect}, which this version does not know"
80
+ end
81
+ entry["unique"] = unique unless unique.nil?
82
+ entry
83
+ end
84
+
85
+ # [kind, element kind, definition, unique items].
86
+ def describe(property)
87
+ if property.key?("PrimitiveType")
88
+ [ primitive(property["PrimitiveType"]), nil, nil, nil ]
89
+ elsif CONTAINERS.include?(property["Type"])
90
+ item, of = element_of(property)
91
+ [ property["Type"] == "List" ? :list : :map, item, of,
92
+ property["Type"] == "List" && !property["DuplicatesAllowed"].nil? ? !property["DuplicatesAllowed"] : nil ]
93
+ elsif property["Type"].is_a?(String)
94
+ nested(property["Type"])
95
+ else
96
+ [ :json, nil, nil, nil ]
97
+ end
98
+ end
99
+
100
+ def primitive(name)
101
+ PRIMITIVES[name] or raise RubyCdk::Error, "#{@type_name}: the specification has the primitive type #{name.inspect}, which this version does not know"
102
+ end
103
+
104
+ # A property whose Type names a property type.
105
+ def nested(name)
106
+ type = @specification.property_type(@type_name, name)
107
+ return [ :json, nil, nil, nil ] unless type.is_a?(Hash)
108
+ return [ :nested, nil, name, nil ] if reaches(name)
109
+
110
+ return [ :json, nil, nil, nil ] unless CONTAINERS.include?(type["Type"])
111
+
112
+ item, of = element_of(type)
113
+ [ type["Type"] == "List" ? :list : :map, item, of, nil ]
114
+ end
115
+
116
+ # [element kind, definition] of a List or a Map, from PrimitiveItemType or ItemType.
117
+ def element_of(property)
118
+ return [ primitive(property["PrimitiveItemType"]), nil ] if property.key?("PrimitiveItemType")
119
+
120
+ name = property["ItemType"]
121
+ return [ :json, nil ] unless name.is_a?(String)
122
+
123
+ type = @specification.property_type(@type_name, name)
124
+ return [ :nested, name ] if reaches(name)
125
+ return [ type["Type"] == "List" ? :list : :map, nil ] if type.is_a?(Hash) && CONTAINERS.include?(type["Type"])
126
+
127
+ [ :json, nil ]
128
+ end
129
+
130
+ # True when the specification defines `name` as a type with named properties, which
131
+ # drain then writes as a definition.
132
+ def reaches(name)
133
+ type = @specification.property_type(@type_name, name)
134
+ return false unless type.is_a?(Hash) && type["Properties"].is_a?(Hash)
135
+
136
+ @queue << name unless @queue.include?(name) || @definitions.key?(name)
137
+ true
138
+ end
139
+
140
+ # Builds every definition an entry reached, and those they reach.
141
+ def drain
142
+ until @queue.empty?
143
+ name = @queue.shift
144
+ next if @definitions.key?(name)
145
+
146
+ type = @specification.property_type(@type_name, name)
147
+ raise RubyCdk::Error, "#{@type_name}: the specification names the property type #{name}, which it does not define" unless type.is_a?(Hash) && type["Properties"].is_a?(Hash)
148
+
149
+ properties = type["Properties"]
150
+ @definitions[name] = {
151
+ "required" => properties.select { |_, property| property["Required"] }.keys.sort,
152
+ "properties" => properties.map { |property_name, property| [ property_name, entry(property) ] }
153
+ }
154
+ end
155
+ end
156
+ end
157
+ end
158
+ end
159
+ end
@@ -0,0 +1,178 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "fileutils"
5
+ require "json"
6
+ require "zlib"
7
+ require_relative "../../schema"
8
+ require_relative "compiler"
9
+ require_relative "download"
10
+ require_relative "provider_schemas"
11
+ require_relative "regions"
12
+ require_relative "resource_specification"
13
+
14
+ module RubyCdk
15
+ module Schema
16
+ module Sources
17
+ # What one run of the update did.
18
+ #
19
+ # region the region the sources were taken from
20
+ # dir where data/spec is
21
+ # changed whether the model's content differed from the file's, and so was written
22
+ # model_sha256 SHA-256 of the model's JSON, the uncompressed bytes
23
+ # model_bytes the size of the model's JSON
24
+ # gzip_bytes the size of model.json.gz
25
+ # meta META.json as a Hash
26
+ Result = Data.define(:region, :dir, :changed, :model_sha256, :model_bytes, :gzip_bytes, :meta) do
27
+ # The lines the rake task prints.
28
+ def summary
29
+ provider = meta.dig("sources", "provider_schemas")
30
+ specification = meta.dig("sources", "resource_specification")
31
+ counts = meta.fetch("counts")
32
+ model = File.join(dir, RubyCdk::Schema::MODEL_FILE)
33
+ [
34
+ "spec: #{region}: provider schemas, #{provider.fetch("types")} types, last modified #{provider.fetch("last_modified")}; " \
35
+ "resource specification, #{specification.fetch("types")} types, version #{meta.fetch("specification_version")}, " \
36
+ "last modified #{specification.fetch("last_modified")}",
37
+ "spec: model: #{counts.fetch("types")} types (#{counts.fetch("only_provider_schemas")} only in the provider schemas, " \
38
+ "#{counts.fetch("only_resource_specification")} only in the specification); #{model_bytes} bytes of JSON, " \
39
+ "#{gzip_bytes} bytes gzipped; sha256 #{model_sha256}",
40
+ changed ? "spec: wrote #{model} and #{File.join(dir, RubyCdk::Schema::META_FILE)}" : "spec: unchanged: #{model} already holds this model, nothing written",
41
+ "spec: schema_version: #{meta.fetch("schema_version")}"
42
+ ].join("\n")
43
+ end
44
+ end
45
+
46
+ class << self
47
+ # Downloads both sources for one region, judges them, compiles the model and writes
48
+ # data/spec under dir, only when the model's content changed.
49
+ #
50
+ # It always downloads: the sources are the only place that says whether they moved,
51
+ # so a run that ends in "unchanged" has asked both of them. It never deletes or
52
+ # rewrites anything before a download has succeeded and been compiled.
53
+ #
54
+ # get is anything that takes a URL and answers a Download; the default is the real
55
+ # one. now is the clock the ninety-day rule is judged against.
56
+ #
57
+ # Raises Regions::Unknown, SourceUnavailable (a source that cannot be reached, a
58
+ # 404, a stale source, a body that is not what it should be), or RubyCdk::Error for
59
+ # content this compiler cannot read. Nothing is written in any of those cases.
60
+ def update(region:, dir:, get: Fetcher.new, now: Time.now)
61
+ urls = Regions.urls(region)
62
+ downloads = urls.transform_values { |url| fetch(url, get) }
63
+
64
+ judge = Fetcher.new
65
+ problems = downloads.values.flat_map { |download| judge.problems(download, now:) }
66
+ raise SourceUnavailable.new(problems) if problems.any?
67
+
68
+ provider_schemas = provider_schemas(downloads.fetch(:provider_schemas))
69
+ specification = specification(downloads.fetch(:resource_specification))
70
+ compiled = Compiler.new(provider_schemas:, specification:).call(region:)
71
+
72
+ json = JSON.generate(compiled.model, sort_keys: true)
73
+ sha256 = Digest::SHA256.hexdigest(json)
74
+ meta = meta(region:, downloads:, compiled:, sha256:, provider_schemas:, specification:)
75
+ changed = sha256 != existing_sha256(dir) || existing_meta_format(dir) != RubyCdk::Schema::META_FORMAT
76
+ gz = changed ? write(dir, json, meta) : File.binread(File.join(dir, RubyCdk::Schema::MODEL_FILE))
77
+
78
+ Result.new(region:, dir:, changed:, model_sha256: sha256, model_bytes: json.bytesize, gzip_bytes: gz.bytesize, meta:)
79
+ end
80
+
81
+ private
82
+
83
+ # A machine that is offline, or a source that does not answer, is one clear line
84
+ # and not a backtrace.
85
+ def fetch(url, get)
86
+ get.call(url)
87
+ rescue RubyCdk::Error
88
+ raise
89
+ rescue StandardError => error
90
+ raise SourceUnavailable.new([ "#{url}: could not be fetched (#{error.class}: #{error.message})" ])
91
+ end
92
+
93
+ def provider_schemas(download)
94
+ ProviderSchemas.parse(download.body)
95
+ rescue Zip::Error
96
+ raise SourceUnavailable.new([ "#{download.url}: what it serves is not a zip archive" ])
97
+ end
98
+
99
+ def specification(download)
100
+ ResourceSpecification.parse(download.body)
101
+ end
102
+
103
+ # The two files are written together, and only when the model changed or META.json
104
+ # is missing or of another format: a source that AWS re-compresses without
105
+ # changing its content produces no diff.
106
+ def existing_sha256(dir)
107
+ Digest::SHA256.hexdigest(Zlib.gunzip(File.binread(File.join(dir, RubyCdk::Schema::MODEL_FILE))))
108
+ rescue Errno::ENOENT, Zlib::GzipFile::Error
109
+ nil
110
+ end
111
+
112
+ # nil when there is no META.json under dir, or none that can be read.
113
+ def existing_meta_format(dir)
114
+ JSON.parse(File.read(File.join(dir, RubyCdk::Schema::META_FILE)))["meta_format"]
115
+ rescue Errno::ENOENT, JSON::ParserError, TypeError
116
+ nil
117
+ end
118
+
119
+ def write(dir, json, meta)
120
+ FileUtils.mkdir_p(dir)
121
+ gz = gzip(json)
122
+ File.binwrite(File.join(dir, RubyCdk::Schema::MODEL_FILE), gz)
123
+ File.write(File.join(dir, RubyCdk::Schema::META_FILE), JSON.pretty_generate(meta, sort_keys: true) + "\n")
124
+ gz
125
+ end
126
+
127
+ # gzip with a zero modification time and no operating-system mark, so that the same
128
+ # model gives the same bytes on every machine.
129
+ def gzip(json)
130
+ gz = Zlib.gzip(json)
131
+ gz[4, 4] = "\0\0\0\0"
132
+ gz.setbyte(9, 255)
133
+ gz
134
+ end
135
+
136
+ def meta(region:, downloads:, compiled:, sha256:, provider_schemas:, specification:)
137
+ provider = downloads.fetch(:provider_schemas)
138
+ {
139
+ "region" => region,
140
+ "meta_format" => RubyCdk::Schema::META_FORMAT,
141
+ "model_format" => RubyCdk::Schema::MODEL_FORMAT,
142
+ "model_sha256" => sha256,
143
+ "schema_version" => schema_version(specification:, sha256:),
144
+ "specification_version" => specification.version,
145
+ "counts" => compiled.counts,
146
+ "sources" => {
147
+ "provider_schemas" => source(provider, types: provider_schemas.size),
148
+ "resource_specification" => source(downloads.fetch(:resource_specification), types: specification.resource_types.size)
149
+ }
150
+ }
151
+ end
152
+
153
+ # What the manifest records as schema_version, in one String: the version of the
154
+ # resource specification, the identity of the model, and the format a loader must
155
+ # speak. It changes exactly when the model does. The provider schemas have no
156
+ # version number, and their Last-Modified is not put here on purpose: AWS
157
+ # republishes the zip with other bytes but the same schemas several times a day,
158
+ # which moves that moment and not the model. It stays in META.json.
159
+ def schema_version(specification:, sha256:)
160
+ "resource specification #{specification.version}, model sha256:#{sha256}, model format #{RubyCdk::Schema::MODEL_FORMAT}"
161
+ end
162
+
163
+ # What one source was: its address, when AWS last changed it, its ETag, and the
164
+ # SHA-256 of the bytes as served.
165
+ def source(download, types:)
166
+ {
167
+ "url" => download.url,
168
+ "last_modified" => download.last_modified&.strftime("%Y-%m-%dT%H:%M:%SZ"),
169
+ "etag" => download.etag,
170
+ "sha256" => Digest::SHA256.hexdigest(download.body),
171
+ "bytes" => download.body.bytesize,
172
+ "types" => types
173
+ }
174
+ end
175
+ end
176
+ end
177
+ end
178
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "sources/compiler"
4
+ require_relative "sources/download"
5
+ require_relative "sources/provider_schemas"
6
+ require_relative "sources/regions"
7
+ require_relative "sources/resource_specification"
8
+ require_relative "sources/update"
9
+
10
+ module RubyCdk
11
+ module Schema
12
+ # Builds data/spec from the two sources AWS publishes. Only `rake spec:update` loads
13
+ # this file: it needs the network, and synthesis never does.
14
+ #
15
+ # RubyCdk::Schema::Sources.update(region: "us-east-1", dir: "data/spec")
16
+ module Sources
17
+ private_constant :ProviderType, :SpecificationType
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,109 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "property_schema"
4
+
5
+ module RubyCdk
6
+ module Schema
7
+ # A nested property type: what a property of kind :nested holds. Reached by name
8
+ # through TypeSchema#definitions, with the key the property's `definition` gives.
9
+ #
10
+ # name the key in TypeSchema#definitions
11
+ # properties Hash of name to PropertySchema, in the source's order
12
+ # required the properties the nested type lists as required
13
+ Definition = Data.define(:name, :properties, :required)
14
+
15
+ # One resource type as the vendored model describes it. Everything here is frozen.
16
+ #
17
+ # name "AWS::Lambda::Function"
18
+ # properties Hash of name to PropertySchema, in the source's order
19
+ # definitions Hash of name to Definition
20
+ # required the properties a template must set
21
+ # create_only property paths that cannot change after creation: "FunctionName", "Code.S3Bucket"
22
+ # read_only property paths only Fn::GetAtt may read: "Arn", "SnapStartResponse.ApplyOn"
23
+ # documentation_url the page AWS documents the type on, or nil when no source has one
24
+ # source :provider when the provider schema described the properties, :specification otherwise
25
+ class TypeSchema
26
+ # How much an update behaviour costs. The behaviour of a path is the costliest along it.
27
+ SEVERITY = { mutable: 0, conditional: 1, immutable: 2 }.freeze
28
+
29
+ # An index inside a list, as a segment of a path written as a String.
30
+ INDEX = /\A\d+\z/
31
+
32
+ attr_reader :name, :properties, :definitions, :required, :create_only, :read_only, :documentation_url, :source
33
+
34
+ def initialize(name:, properties:, definitions:, required:, create_only:, read_only:, documentation_url:, source:, additional_properties: false)
35
+ @name = name
36
+ @properties = properties
37
+ @definitions = definitions
38
+ @required = required
39
+ @create_only = create_only
40
+ @read_only = read_only
41
+ @documentation_url = documentation_url
42
+ @source = source
43
+ @additional_properties = additional_properties
44
+ freeze
45
+ end
46
+
47
+ # True when the source lets a template set properties it does not list, as
48
+ # AWS::CloudFormation::CustomResource does.
49
+ def additional_properties?
50
+ @additional_properties
51
+ end
52
+
53
+ # The update behaviour of a property path: :mutable, :immutable, :conditional,
54
+ # or :unknown when the path does not name a property of this type, or ends at a
55
+ # read-only one, which nothing updates.
56
+ #
57
+ # The answer is the costliest behaviour from the top-level property down to the
58
+ # path's end, because changing a property inside an immutable one replaces the
59
+ # resource as surely as changing the immutable one. "KeySchema[0].AttributeName"
60
+ # is immutable although AttributeName alone is mutable.
61
+ #
62
+ # path is a dotted String ("Code.S3Bucket") or an Array of segments, where an
63
+ # Integer indexes a list: [:code, 0, "S3Bucket"]. A path that goes deeper than
64
+ # the schema describes, into a :json value or past a scalar, answers with the
65
+ # behaviour of the last property it named.
66
+ def update_behaviour(path)
67
+ costliest_along(segments_of(path), self, :unknown)
68
+ end
69
+
70
+ private
71
+
72
+ # The costliest behaviour from the property that names the first segment on down
73
+ # the rest of the path. container is what holds that first segment.
74
+ def costliest_along(segments, container, behaviour)
75
+ return behaviour if segments.empty?
76
+
77
+ property = container.properties[segments.first] or return :unknown
78
+ return :unknown if property.update_behaviour == :unknown
79
+
80
+ behaviour = costlier(behaviour, property.update_behaviour)
81
+ return behaviour unless property.item_kind == :nested || property.kind == :nested
82
+
83
+ nested = definitions[property.definition] or return behaviour
84
+ costliest_along(past_the_element(property, segments.drop(1)), nested, behaviour)
85
+ end
86
+
87
+ def costlier(left, right)
88
+ SEVERITY.fetch(right) >= SEVERITY.fetch(left, -1) ? right : left
89
+ end
90
+
91
+ # The rest of a path once a list's index or a map's key is left behind.
92
+ def past_the_element(property, rest)
93
+ return rest if rest.empty?
94
+ return rest.drop(1) if property.kind == :map
95
+ return rest.drop(1) if property.kind == :list && rest.first.match?(INDEX)
96
+
97
+ rest
98
+ end
99
+
100
+ def segments_of(path)
101
+ case path
102
+ when String then path.split(".")
103
+ when Array then path.map(&:to_s)
104
+ else Array(path.to_s)
105
+ end
106
+ end
107
+ end
108
+ end
109
+ end