ruby-cdk 0.2.0 → 0.3.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 (47) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +253 -0
  3. data/README.md +28 -5
  4. data/lib/ruby_cdk/assets/hasher.rb +4 -0
  5. data/lib/ruby_cdk/assets.rb +4 -8
  6. data/lib/ruby_cdk/cli/aws.rb +23 -5
  7. data/lib/ruby_cdk/cli/drift.rb +94 -0
  8. data/lib/ruby_cdk/cli/import.rb +306 -0
  9. data/lib/ruby_cdk/cli/lookup.rb +214 -0
  10. data/lib/ruby_cdk/cli/session.rb +114 -3
  11. data/lib/ruby_cdk/cli/watch.rb +297 -0
  12. data/lib/ruby_cdk/cli.rb +76 -1
  13. data/lib/ruby_cdk/constructs/function.rb +24 -3
  14. data/lib/ruby_cdk/constructs/hosted_zone.rb +342 -0
  15. data/lib/ruby_cdk/constructs/record_set.rb +330 -0
  16. data/lib/ruby_cdk/constructs/ssm_parameter.rb +174 -0
  17. data/lib/ruby_cdk/constructs/vpc.rb +822 -0
  18. data/lib/ruby_cdk/constructs/vpc_network.rb +159 -0
  19. data/lib/ruby_cdk/constructs.rb +5 -1
  20. data/lib/ruby_cdk/core/app.rb +28 -2
  21. data/lib/ruby_cdk/core/construct.rb +2 -0
  22. data/lib/ruby_cdk/core/context.rb +138 -0
  23. data/lib/ruby_cdk/core/stack.rb +4 -0
  24. data/lib/ruby_cdk/core.rb +1 -0
  25. data/lib/ruby_cdk/deploy/deployer.rb +283 -8
  26. data/lib/ruby_cdk/deploy/drift.rb +389 -0
  27. data/lib/ruby_cdk/deploy/ec2_adapter.rb +214 -0
  28. data/lib/ruby_cdk/deploy/errors.rb +8 -0
  29. data/lib/ruby_cdk/deploy/fakes.rb +230 -22
  30. data/lib/ruby_cdk/deploy/output/base.rb +8 -0
  31. data/lib/ruby_cdk/deploy/output/json.rb +7 -0
  32. data/lib/ruby_cdk/deploy/poller.rb +10 -0
  33. data/lib/ruby_cdk/deploy/ports.rb +124 -8
  34. data/lib/ruby_cdk/deploy/sdk_adapters.rb +141 -6
  35. data/lib/ruby_cdk/deploy/ssm_adapter.rb +111 -0
  36. data/lib/ruby_cdk/deploy.rb +1 -0
  37. data/lib/ruby_cdk/diff/compare.rb +1 -1
  38. data/lib/ruby_cdk/diff/identity_center.rb +64 -0
  39. data/lib/ruby_cdk/diff/render.rb +147 -8
  40. data/lib/ruby_cdk/diff/security.rb +195 -10
  41. data/lib/ruby_cdk/diff/security_group.rb +94 -0
  42. data/lib/ruby_cdk/nag/rules/security_group_ingress.rb +2 -0
  43. data/lib/ruby_cdk/schema/sources/provider_type.rb +3 -0
  44. data/lib/ruby_cdk/test/private/cyclic.rb +4 -0
  45. data/lib/ruby_cdk/test/private/js.rb +1 -3
  46. data/lib/ruby_cdk/version.rb +1 -1
  47. metadata +43 -1
@@ -0,0 +1,342 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+ require_relative "../fn"
5
+ require_relative "../lazy"
6
+
7
+ module RubyCdk
8
+ module Route53
9
+ # A Route 53 hosted zone: the port of the CDK's HostedZone
10
+ # (aws-route53/lib/hosted-zone.ts), read at commit
11
+ # c070afb54b9e4dbddd52a85a21077fe970354985, Apache-2.0.
12
+ #
13
+ # RubyCdk::Route53::HostedZone.new(stack, "Zone", zone_name: "example.com")
14
+ # RubyCdk::Route53::HostedZone.new(stack, "Private",
15
+ # zone_name: "example.internal", vpcs: [ RubyCdk::EC2::Vpc.new(self, "Net") ])
16
+ #
17
+ # The zone name is validated against Route 53's rules as the CDK's
18
+ # validateZoneName validates it (util.ts:15-25): at most 255 characters,
19
+ # every label between the dots at most 63, and only the letters, digits
20
+ # and characters the CDK's pattern lists. The name in the template gets
21
+ # the trailing dot the CDK adds when it is missing
22
+ # (hosted-zone.ts:257-258): zone_name: "example.com" writes Name
23
+ # "example.com." and a name that already ends with a dot is kept;
24
+ # add_trailing_dot: false writes the name as given, as the CDK's
25
+ # addTrailingDot: false does. All four shapes are the origin's
26
+ # "Hosted Zone with dot" cases. The zone_name accessor answers the name
27
+ # as given, without the dot, as the CDK's answers (hosted-zone.ts:269);
28
+ # the dotted one is what the Name property carries, and a record name
29
+ # built against the zone strips it again (record_set.rb, the CDK's
30
+ # determineFullyQualifiedDomainName).
31
+ #
32
+ # The comment travels in HostedZoneConfig.Comment when given and the
33
+ # query-logging ARN in QueryLoggingConfig.CloudWatchLogsLogGroupArn when
34
+ # given, each left out otherwise (hosted-zone.ts:262-263); an empty
35
+ # string counts as not given, as JavaScript's falsy check does in the
36
+ # CDK. query_logs_log_group_arn is the prop of the CDK's
37
+ # queryLogsLogGroupArn, which writes the QueryLoggingConfig of the same
38
+ # resource; there is no separate QueryLoggingConfig resource to carry.
39
+ #
40
+ # vpcs: makes the zone a private one: each entry becomes a VPCs pair of
41
+ # VPCId and VPCRegion (hosted-zone.ts:287-290). An entry is a Vpc
42
+ # construct (created or looked up; both answer vpc_id, the created one
43
+ # as its Ref), a Hash { vpc_id:, region: } - the shape the CDK's
44
+ # fromVpcAttributes result feeds the pair with - or a bare id String.
45
+ # The region is the entry's own when the Hash names one, and otherwise
46
+ # the VPC's stack's concrete region or, when that stack has no env, the
47
+ # AWS::Region reference the CDK's Stack.of(vpc).region resolves to in a
48
+ # template (hosted-zone.ts:289, vpc.env.region ?? Stack.of(vpc).region).
49
+ # A Hash or a bare id has no stack of its own, so its region falls back
50
+ # to the zone's stack. VPCs sits behind a Lazy, so add_vpc after the
51
+ # zone is built works, as the CDK's addVpc does (hosted-zone.ts:287);
52
+ # with no VPCs the property is left out: the public zone.
53
+ #
54
+ # The accessors are the CDK's: zone_id is the Ref of the resource
55
+ # (hosted-zone.ts:267), zone_arn is one Fn::Sub over the ARN the CDK's
56
+ # makeHostedZoneArn builds (util.ts:57-65: arn:<partition>:route53:::
57
+ # hostedzone/<id>, where the CDK renders an Fn::Join over the same
58
+ # parts), name is zone_name (hosted-zone.ts:119-121), and
59
+ # hosted_zone_name_servers is the NameServers GetAtt of the resource
60
+ # (hosted-zone.ts:268).
61
+ #
62
+ # Where this tool differs from the CDK (architecture section 7 wins; the
63
+ # rows are in section 21):
64
+ #
65
+ # - The record sets are the CDK's standalone classes
66
+ # (RubyCdk::Route53::RecordSet and the per-type records of
67
+ # record_set.rb), built with this zone as their scope. The brief
68
+ # of this wave names addARecord-style methods on HostedZone; the
69
+ # source has none - records are their own constructs in
70
+ # aws-route53 (record-set.ts), and the source wins.
71
+ # - grant_delegation is refused: the delegation grant carries the
72
+ # ForAllValues:StringEquals condition of util.ts:131-157, and the
73
+ # Grant here carries actions and ARNs only. Write the two
74
+ # statements (route53:ChangeResourceRecordSets on the zone ARN
75
+ # under the NS/UPSERT/DELETE condition, and
76
+ # route53:ListHostedZonesByName on *) with IAM::PolicyStatement on
77
+ # the principal's policy. The PublicHostedZone pieces around
78
+ # delegation - the delegation role from
79
+ # crossAccountZoneDelegationPrincipal, the CrossAccountZoneDelegationRecord
80
+ # custom resource, addDelegation and the ZoneDelegationRecord it
81
+ # writes - are not carried either: this tool has no custom
82
+ # resources, and the PublicHostedZone and PrivateHostedZone
83
+ # classes are not carried (HostedZone takes vpcs: directly).
84
+ # - enableDnssec and the KeySigningKey and DNSSEC resources it writes
85
+ # (hosted-zone.ts:307-322) are not carried, and neither are the
86
+ # PublicHostedZone-only caaAmazon and acceleratedRecoveryEnabled
87
+ # props, which write a CaaAmazonRecord and the HostedZoneFeatures
88
+ # property.
89
+ class HostedZone < Construct
90
+ # The characters of a zone name, the CDK's validateZoneName pattern
91
+ # (util.ts:22).
92
+ ZONE_NAME_PATTERN = %r{\A[a-z0-9!"#$%&'()*+,.:;<=>?@\[\\\]^_`{|}~/-]+\z}i
93
+
94
+ attr_reader :zone_name
95
+
96
+ # The import the future lookup fills: HostedZone.from_hosted_zone_attributes
97
+ # is the CDK's fromHostedZoneAttributes (hosted-zone.ts:165-184), and
98
+ # the CDK's fromLookup (hosted-zone.ts:194-225) returns exactly it -
99
+ # the id and the name as literals, no resource of its own. Until the
100
+ # hosted-zone lookup rides the context machinery (D-022), the
101
+ # attributes are given by hand.
102
+ def self.from_hosted_zone_attributes(scope, id, zone_id:, zone_name:)
103
+ Imported.import(scope, id, zone_id: zone_id, zone_name: zone_name)
104
+ end
105
+
106
+ def initialize(scope, id, zone_name:, vpcs: nil, comment: nil, query_logs_log_group_arn: nil,
107
+ add_trailing_dot: nil)
108
+ super(scope, id)
109
+ validate_zone_name(zone_name)
110
+ trailing = trailing_dot(add_trailing_dot)
111
+ @zone_name = zone_name
112
+ normalized = trailing && !zone_name.end_with?(".") ? "#{zone_name}." : zone_name
113
+ @vpcs = []
114
+ @resource = resource("Resource", "AWS::Route53::HostedZone",
115
+ Name: normalized,
116
+ HostedZoneConfig: comment_string(comment),
117
+ QueryLoggingConfig: query_logging(query_logs_log_group_arn),
118
+ VPCs: Lazy.new { @vpcs.empty? ? nil : @vpcs })
119
+ given_vpcs(vpcs)
120
+ end
121
+
122
+ # The logical ID of the AWS::Route53::HostedZone under this construct,
123
+ # so that the zone can sit in another resource's depends_on:.
124
+ def logical_id
125
+ @resource.logical_id
126
+ end
127
+
128
+ # The ID of the zone: the Ref of the resource (hosted-zone.ts:267).
129
+ def zone_id
130
+ Fn.ref(@resource)
131
+ end
132
+
133
+ # The zone's ARN, over the pseudo parameters, as the CDK's
134
+ # makeHostedZoneArn renders it in a stack without a concrete env
135
+ # (util.ts:57-65).
136
+ def zone_arn
137
+ Fn.sub("arn:${AWS::Partition}:route53:::hostedzone/${ZoneId}",
138
+ "ZoneId" => zone_id)
139
+ end
140
+
141
+ # The FQDN of the zone, as the CDK's name getter answers it
142
+ # (hosted-zone.ts:119-121): the name as given.
143
+ def name
144
+ @zone_name
145
+ end
146
+
147
+ # The zone's name servers, the NameServers attribute of the resource
148
+ # (hosted-zone.ts:268).
149
+ def hosted_zone_name_servers
150
+ Fn.get_att(@resource, "NameServers")
151
+ end
152
+
153
+ # Adds one VPC to the zone: the entry kinds of vpcs: (see the header).
154
+ def add_vpc(vpc)
155
+ @vpcs << vpc_entry(vpc)
156
+ self
157
+ end
158
+
159
+ # The delegation grant needs a conditioned statement, which the Grant
160
+ # here does not carry; see the header.
161
+ def grant_delegation(_grantee, _options = nil)
162
+ raise UsageError, "#{path}: grant_delegation is not carried: the delegation grant carries the " \
163
+ "ForAllValues:StringEquals condition of the CDK's makeGrantDelegation (util.ts:131-157), and this " \
164
+ "tool's grants carry actions and ARNs only. Put route53:ChangeResourceRecordSets on the zone ARN " \
165
+ "#{zone_arn['Fn::Sub']}, under that condition, and route53:ListHostedZonesByName on *, on the " \
166
+ "principal's policy with IAM::PolicyStatement"
167
+ end
168
+
169
+ private
170
+
171
+ # The CDK's validateZoneName (util.ts:15-25), in its order and with
172
+ # its words.
173
+ def validate_zone_name(name)
174
+ raise UsageError, "#{path}: zone_name takes a String, got #{name.inspect}" unless name.is_a?(String)
175
+ raise UsageError, "#{path}: zone name cannot be more than 255 bytes long" if name.length > 255
176
+ if name.split(".").any? { |label| label.length > 63 }
177
+ raise UsageError, "#{path}: zone name labels cannot be more than 63 bytes long"
178
+ end
179
+ unless ZONE_NAME_PATTERN.match?(name)
180
+ raise UsageError, "#{path}: zone names can only contain a-z, 0-9, -, ! \" # $ % & ' ( ) * + , " \
181
+ "- / : ; < = > ? @ [ \\ ] ^ _ ` { | } ~ ."
182
+ end
183
+ end
184
+
185
+ # addTrailingDot is true unless it is false (hosted-zone.ts:258).
186
+ def trailing_dot(value)
187
+ return true if value.nil?
188
+ return value if value == true || value == false
189
+
190
+ raise UsageError, "#{path}: add_trailing_dot takes true or false, got #{value.inspect}"
191
+ end
192
+
193
+ # hosted-zone.ts:262: the comment, JavaScript-falsy values included.
194
+ def comment_string(comment)
195
+ return nil unless comment.is_a?(String) && !comment.empty?
196
+
197
+ { "Comment" => comment }
198
+ end
199
+
200
+ # hosted-zone.ts:263: the query-logging ARN, JavaScript-falsy values
201
+ # included.
202
+ def query_logging(arn)
203
+ return nil unless arn.is_a?(String) && !arn.empty?
204
+
205
+ { "CloudWatchLogsLogGroupArn" => arn }
206
+ end
207
+
208
+ def given_vpcs(vpcs)
209
+ return if vpcs.nil?
210
+
211
+ raise UsageError, "#{path}: vpcs takes an Array of VPC entries, got #{vpcs.inspect}" unless vpcs.is_a?(Array)
212
+
213
+ vpcs.each { |entry| add_vpc(entry) }
214
+ end
215
+
216
+ # One VPCs pair (hosted-zone.ts:289): the id, and the region - the
217
+ # Hash's own, the construct's stack's concrete one, or the stack's
218
+ # AWS::Region reference.
219
+ def vpc_entry(vpc)
220
+ case vpc
221
+ when Hash
222
+ hash_entry(vpc)
223
+ when String
224
+ raise UsageError, "#{path}: a bare vpc_id String cannot be empty" if vpc.empty?
225
+
226
+ { "VPCId" => vpc, "VPCRegion" => zone_region }
227
+ else
228
+ construct_entry(vpc)
229
+ end
230
+ end
231
+
232
+ def hash_entry(vpc)
233
+ unless (vpc.keys - %i[vpc_id region]).empty? && vpc.key?(:vpc_id)
234
+ raise UsageError, "#{path}: a VPC entry Hash takes vpc_id: and, when the pair is not the stack's " \
235
+ "own, region:, got #{vpc.inspect}"
236
+ end
237
+ unless vpc[:vpc_id].is_a?(String) && !vpc[:vpc_id].empty?
238
+ raise UsageError, "#{path}: a VPC entry takes a non-empty vpc_id String, got #{vpc[:vpc_id].inspect}"
239
+ end
240
+ region = vpc[:region]
241
+ unless region.nil? || (region.is_a?(String) && !region.empty?)
242
+ raise UsageError, "#{path}: a VPC entry takes a non-empty region String, got #{region.inspect}"
243
+ end
244
+
245
+ { "VPCId" => vpc[:vpc_id], "VPCRegion" => region || zone_region }
246
+ end
247
+
248
+ def construct_entry(vpc)
249
+ unless vpc.respond_to?(:vpc_id)
250
+ raise UsageError, "#{path}: a VPC entry is a Vpc (created or looked up), a Hash { vpc_id:, region: } " \
251
+ "or a bare id String, got #{vpc.inspect}"
252
+ end
253
+ stack = vpc.respond_to?(:stack) ? vpc.stack : nil
254
+ unless stack
255
+ raise UsageError, "#{path}: a VPC entry is built in a Stack: got #{vpc.inspect}, which has none"
256
+ end
257
+
258
+ { "VPCId" => vpc.vpc_id, "VPCRegion" => stack.env&.region || Fn.ref("AWS::Region") }
259
+ end
260
+
261
+ def zone_region
262
+ stack.env&.region || Fn.ref("AWS::Region")
263
+ end
264
+ end
265
+
266
+ # The imported zone (the CDK's Import of fromHostedZoneAttributes,
267
+ # hosted-zone.ts:165-184): a tree node that synthesizes no resources,
268
+ # answering the literals it was given - the id, the name, the name
269
+ # again as the FQDN, and the ARN built over the literal id as the
270
+ # created zone builds it over its Ref. The hosted-zone lookup the
271
+ # context machinery will one day carry (D-022) returns this shape, as
272
+ # the CDK's fromLookup returns fromHostedZoneAttributes' Import
273
+ # (hosted-zone.ts:221-224).
274
+ #
275
+ # What it does not grant, each a refusal that says so: grant_delegation
276
+ # (the same conditioned statement the created zone refuses; this tool
277
+ # grants to identities only, with IAM::PolicyStatement), add_vpc (the
278
+ # import has no VPCs of its own, as the CDK's Import has no addVpc),
279
+ # hosted_zone_name_servers (the attributes do not name the name
280
+ # servers) and logical_id (nothing of this stack carries it).
281
+ class HostedZone
282
+ class Imported < Construct
283
+ def self.import(scope, id, zone_id:, zone_name:)
284
+ where = "HostedZone.from_hosted_zone_attributes #{id.inspect}"
285
+ unless zone_id.is_a?(String) && !zone_id.empty?
286
+ raise UsageError, "#{where}: zone_id takes a non-empty String, got #{zone_id.inspect}"
287
+ end
288
+ unless zone_name.is_a?(String) && !zone_name.empty?
289
+ raise UsageError, "#{where}: zone_name takes a non-empty String, got #{zone_name.inspect}"
290
+ end
291
+
292
+ new(scope, id, zone_id:, zone_name:)
293
+ end
294
+
295
+ def initialize(scope, id, zone_id:, zone_name:)
296
+ super(scope, id)
297
+ @zone_id = zone_id
298
+ @zone_name = zone_name
299
+ end
300
+
301
+ def zone_id
302
+ @zone_id
303
+ end
304
+
305
+ def zone_name
306
+ @zone_name
307
+ end
308
+
309
+ def name
310
+ @zone_name
311
+ end
312
+
313
+ def zone_arn
314
+ Fn.sub("arn:${AWS::Partition}:route53:::hostedzone/${ZoneId}", "ZoneId" => @zone_id)
315
+ end
316
+
317
+ def grant_delegation(_grantee, _options = nil)
318
+ raise UsageError, "#{path}: grant_delegation is not carried: the delegation grant carries the " \
319
+ "ForAllValues:StringEquals condition of the CDK's makeGrantDelegation (util.ts:131-157), and this " \
320
+ "tool's grants carry actions and ARNs only. Put route53:ChangeResourceRecordSets on the zone ARN " \
321
+ "#{zone_arn['Fn::Sub']}, under that condition, and route53:ListHostedZonesByName on *, on the " \
322
+ "principal's policy with IAM::PolicyStatement"
323
+ end
324
+
325
+ def add_vpc(_vpc)
326
+ raise UsageError, "#{path}: an imported zone associates no VPCs: the zone exists, and its VPCs " \
327
+ "belong to it. Pass vpcs: when you create a zone, or write the VPCs pair into the template directly"
328
+ end
329
+
330
+ def hosted_zone_name_servers
331
+ raise UsageError, "#{path}: an imported zone answers no hosted_zone_name_servers: the attributes " \
332
+ "carry the id and the name, and the name servers are read from the zone, not given"
333
+ end
334
+
335
+ def logical_id
336
+ raise UsageError, "#{path}: an imported zone synthesizes no resources, so it answers no logical_id; " \
337
+ "use #{path}.zone_id where a Ref was meant"
338
+ end
339
+ end
340
+ end
341
+ end
342
+ end
@@ -0,0 +1,330 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "../errors"
5
+ require_relative "../fn"
6
+ require_relative "../lazy"
7
+
8
+ module RubyCdk
9
+ module Route53
10
+ # The record types the CDK's RecordType enum names (record-set.ts:36-170).
11
+ RECORD_TYPES = %w[
12
+ A AAAA CAA CNAME DS HTTPS MX NAPTR NS PTR SOA SPF SRV SSHFP SVCB TLSA TXT
13
+ ].freeze
14
+
15
+ # The CAA tags of the CDK's CaaTag enum (record-set.ts:830-848).
16
+ CAA_TAGS = { issue: "issue", issuewild: "issuewild", iodef: "iodef" }.freeze
17
+
18
+ # The CDK's determineFullyQualifiedDomainName (aws-route53/lib/util.ts:42-55),
19
+ # the record-name domain-ification: a name ending with a dot is used
20
+ # as-is; a name that already ends with the zone name, or is the zone
21
+ # name, takes only the trailing dot; anything else gets the zone name
22
+ # and the dots appended. The zone name is compared without its own
23
+ # trailing dot.
24
+ def self.determine_fully_qualified_domain_name(provided_name, zone)
25
+ return provided_name if provided_name.end_with?(".")
26
+
27
+ hosted_zone_name = zone.zone_name.sub(/\.\z/, "")
28
+ suffix = ".#{hosted_zone_name}"
29
+ provided_name.end_with?(suffix) || provided_name == hosted_zone_name ? "#{provided_name}." : "#{provided_name}#{suffix}."
30
+ end
31
+
32
+ # A record set: the port of the CDK's RecordSet (aws-route53/lib/record-set.ts),
33
+ # read at commit c070afb54b9e4dbddd52a85a21077fe970354985, Apache-2.0.
34
+ #
35
+ # RubyCdk::Route53::RecordSet.new(zone, "Basic",
36
+ # record_type: :cname, record_name: "www", values: ["zzz"])
37
+ #
38
+ # It writes one AWS::Route53::RecordSet under the zone's namespace
39
+ # (D-029): the logical ID is the zone's path, the record's id, then
40
+ # Resource. The zone is the scope - RecordSet.new(zone, id, ...), the
41
+ # CDK's own props.zone - and it is anything that answers zone_id and
42
+ # zone_name: a created, imported or looked-up HostedZone. The record
43
+ # name is qualified
44
+ # against the zone with determine_fully_qualified_domain_name above
45
+ # (record-set.ts:457, the name given or the zone root), the type is one
46
+ # of the CDK's RecordType values, and the values are the resource
47
+ # records (record-set.ts:463). The TTL is a whole number of seconds,
48
+ # 1800 by default, as the CDK's Duration.minutes(30) is
49
+ # (record-set.ts:452); a given 0 is kept, as the CDK keeps it, and it
50
+ # travels as the string the property is (record-set.ts:452). There is
51
+ # no UPSERT anywhere to port: the CDK writes no action into the record
52
+ # set, the resource type has no Action property (the vendored model
53
+ # lists none), and CloudFormation upserts a record set it creates or
54
+ # changes and deletes it with the stack; the CDK's UPSERT strings
55
+ # belong to the delegation grant's IAM condition and to a custom
56
+ # resource, neither of which is a record write.
57
+ #
58
+ # The CDK's target is a RecordTarget - values or an alias. The alias
59
+ # side needs an IAliasRecordTarget class per target kind (the
60
+ # aws-route53-targets package builds them), so it is not carried: this
61
+ # wave carries the values side, which is what
62
+ # RecordTarget.fromValues/fromIpAddresses write. An alias target arrives
63
+ # with the target classes, and with it the AliasTarget property and the
64
+ # ttl-ignored warning of record-set.ts:453-455.
65
+ #
66
+ # Where this tool differs from the CDK (architecture section 7 wins;
67
+ # the rows are in section 21), the options not carried, each named here
68
+ # where the reader meets them: the routing policies - weight, region,
69
+ # geoLocation, multiValueAnswer, failover, cidrRoutingConfig,
70
+ # setIdentifier - with the six validations they feed
71
+ # (record-set.ts:406-443), healthCheck (no HealthCheck construct here),
72
+ # deleteExisting (deprecated; it writes the
73
+ # Custom::DeleteExistingRecordSet custom resource of record-set.ts:483-522),
74
+ # and the DS, ZoneDelegation, SVCB and HTTPS record classes beside this
75
+ # one. The comment travels in Comment when given, left out otherwise.
76
+ #
77
+ # The accessors are the CDK's: domain_name is the Ref of the record set
78
+ # (record-set.ts:481, its domainName) and logical_id the resource's.
79
+ class RecordSet < Construct
80
+ # The default TTL (record-set.ts:452, Duration.minutes(30)).
81
+ DEFAULT_TTL = 1800
82
+
83
+ attr_reader :record_type
84
+
85
+ def initialize(scope, id, record_type:, values:, record_name: nil, ttl: nil, comment: nil)
86
+ super(scope, id)
87
+ @zone = valid_zone(scope)
88
+ @record_type = valid_record_type(record_type)
89
+ @values = valid_values(values)
90
+
91
+ @resource = resource("Resource", "AWS::Route53::RecordSet",
92
+ HostedZoneId: @zone.zone_id,
93
+ Name: Route53.determine_fully_qualified_domain_name(name_of(record_name), @zone),
94
+ Type: @record_type,
95
+ ResourceRecords: @values,
96
+ TTL: (valid_ttl(ttl) || DEFAULT_TTL).to_s,
97
+ Comment: valid_comment(comment))
98
+ end
99
+
100
+ # The logical ID of the AWS::Route53::RecordSet under the zone, so
101
+ # that the record can sit in another resource's depends_on:.
102
+ def logical_id
103
+ @resource.logical_id
104
+ end
105
+
106
+ # The domain name of the record: the Ref of the resource
107
+ # (record-set.ts:481).
108
+ def domain_name
109
+ Fn.ref(@resource)
110
+ end
111
+
112
+ private
113
+
114
+ def valid_zone(zone)
115
+ return zone if zone.respond_to?(:zone_id) && zone.respond_to?(:zone_name) && zone.zone_name.is_a?(String)
116
+
117
+ raise UsageError, "#{path}: the scope of a record is its zone - a created, imported or looked-up " \
118
+ "HostedZone - got #{zone.inspect}"
119
+ end
120
+
121
+ # A Symbol or a String of the CDK's RecordType (record-set.ts:36-170);
122
+ # the type travels as the enum's value spells it, in capitals.
123
+ def valid_record_type(value)
124
+ name = value.is_a?(Symbol) ? value.name : value
125
+ return name.upcase if name.is_a?(String) && RECORD_TYPES.include?(name.upcase)
126
+
127
+ raise UsageError, "#{path}: record_type takes one of #{RECORD_TYPES.join(", ")}, got #{value.inspect}"
128
+ end
129
+
130
+ # The resource records (record-set.ts:463): a non-empty list of
131
+ # strings or of intrinsics, as the CDK's RecordTarget.fromValues
132
+ # takes.
133
+ def valid_values(values)
134
+ unless values.is_a?(Array) && !values.empty?
135
+ raise UsageError, "#{path}: values takes a non-empty Array of records, got #{values.inspect}"
136
+ end
137
+ values.each do |value|
138
+ unless value.is_a?(String) || value.is_a?(Hash) || value.is_a?(Lazy)
139
+ raise UsageError, "#{path}: each value is a String, an intrinsic or a Lazy, got #{value.inspect}"
140
+ end
141
+ end
142
+
143
+ values
144
+ end
145
+
146
+ # A whole number of seconds (record-set.ts:452, the CDK's
147
+ # ttl.toSeconds()).
148
+ def valid_ttl(value)
149
+ return nil if value.nil?
150
+ return value if value.is_a?(Integer) && value >= 0
151
+
152
+ raise UsageError, "#{path}: ttl takes a whole number of seconds, got #{value.inspect}"
153
+ end
154
+
155
+ def valid_comment(value)
156
+ return nil if value.nil?
157
+ return value if value.is_a?(String)
158
+
159
+ raise UsageError, "#{path}: comment takes a String, got #{value.inspect}"
160
+ end
161
+
162
+ # The record name: the one given, or the zone root, as the CDK's
163
+ # props.recordName || props.zone.zoneName reads it
164
+ # (record-set.ts:457), JavaScript-falsy values included.
165
+ def name_of(record_name)
166
+ return record_name if record_name.is_a?(String) && !record_name.empty?
167
+
168
+ @zone.zone_name
169
+ end
170
+ end
171
+
172
+ # The DNS A record: the CDK's ARecord (record-set.ts:609-639), type A,
173
+ # the values the IP addresses of RecordTarget.fromIpAddresses.
174
+ class ARecord < RecordSet
175
+ def initialize(zone, id, record_name: nil, values:, ttl: nil, comment: nil)
176
+ super(zone, id, record_type: "A", values:, record_name:, ttl:, comment:)
177
+ end
178
+ end
179
+
180
+ # The DNS AAAA record: the CDK's AaaaRecord (record-set.ts:675-688).
181
+ class AaaaRecord < RecordSet
182
+ def initialize(zone, id, record_name: nil, values:, ttl: nil, comment: nil)
183
+ super(zone, id, record_type: "AAAA", values:, record_name:, ttl:, comment:)
184
+ end
185
+ end
186
+
187
+ # The DNS CNAME record: the CDK's CnameRecord (record-set.ts:706-719),
188
+ # one value, the domain name the record points at.
189
+ class CnameRecord < RecordSet
190
+ def initialize(zone, id, domain_name:, record_name: nil, ttl: nil, comment: nil)
191
+ super(zone, id, record_type: "CNAME", values: [ domain_name ], record_name:, ttl:, comment:)
192
+ end
193
+ end
194
+
195
+ # The DNS TXT record: the CDK's TxtRecord (record-set.ts:737-750). Each
196
+ # value is a literal string, escaped and enclosed in double quotes by
197
+ # the CDK's formatTxt (record-set.ts:763-770), and a value longer than
198
+ # 255 characters is split into 255-character chunks, each quoted, as
199
+ # DNS TXT strings must be.
200
+ class TxtRecord < RecordSet
201
+ def initialize(zone, id, values:, record_name: nil, ttl: nil, comment: nil)
202
+ unless values.is_a?(Array) && values.all? { |value| value.is_a?(String) }
203
+ raise UsageError, "#{path}: values takes an Array of literal Strings - the CDK's formatTxt cuts " \
204
+ "them into 255-character chunks where it stands (record-set.ts:763-770) - got #{values.inspect}"
205
+ end
206
+
207
+ super(zone, id, record_type: "TXT", values: values.map { |value| format_txt(value) },
208
+ record_name:, ttl:, comment:)
209
+ end
210
+
211
+ private
212
+
213
+ # formatTxt (record-set.ts:763-770): 255-character chunks, each
214
+ # JSON-escaped and quoted, joined.
215
+ def format_txt(value)
216
+ chunks = []
217
+ index = 0
218
+ while index < value.length
219
+ chunks << value[index, 255]
220
+ index += 255
221
+ end
222
+
223
+ chunks.map { |chunk| JSON.generate(chunk) }.join
224
+ end
225
+ end
226
+
227
+ # The DNS SRV record: the CDK's SrvRecord (record-set.ts:812-825). Each
228
+ # value is a Hash { priority:, weight:, port:, host_name: }, rendered
229
+ # as the four space-separated fields the record carries.
230
+ class SrvRecord < RecordSet
231
+ def initialize(zone, id, values:, record_name: nil, ttl: nil, comment: nil)
232
+ super(zone, id, record_type: "SRV", values: values.map { |value| srv_value(value) },
233
+ record_name:, ttl:, comment:)
234
+ end
235
+
236
+ private
237
+
238
+ def srv_value(value)
239
+ unless value.is_a?(Hash) && (%i[priority weight port host_name] - value.keys).empty?
240
+ raise UsageError, "#{path}: each SRV value is a Hash { priority:, weight:, port:, host_name: }, " \
241
+ "got #{value.inspect}"
242
+ end
243
+ %i[priority weight port].each do |field|
244
+ unless value[field].is_a?(Integer)
245
+ raise UsageError, "#{path}: the SRV #{field} is a whole number, got #{value[field].inspect}"
246
+ end
247
+ end
248
+ unless value[:host_name].is_a?(String) && !value[:host_name].empty?
249
+ raise UsageError, "#{path}: the SRV host_name is a String, got #{value[:host_name].inspect}"
250
+ end
251
+
252
+ "#{value[:priority]} #{value[:weight]} #{value[:port]} #{value[:host_name]}"
253
+ end
254
+ end
255
+
256
+ # The DNS CAA record: the CDK's CaaRecord (record-set.ts:886-899). Each
257
+ # value is a Hash { flag:, tag:, value: }, rendered as "flag tag
258
+ # \"value\"", the tag one of the CaaTag values.
259
+ class CaaRecord < RecordSet
260
+ def initialize(zone, id, values:, record_name: nil, ttl: nil, comment: nil)
261
+ super(zone, id, record_type: "CAA", values: values.map { |value| caa_value(value) },
262
+ record_name:, ttl:, comment:)
263
+ end
264
+
265
+ private
266
+
267
+ def caa_value(value)
268
+ unless value.is_a?(Hash) && (%i[flag tag value] - value.keys).empty?
269
+ raise UsageError, "#{path}: each CAA value is a Hash { flag:, tag:, value: }, got #{value.inspect}"
270
+ end
271
+ unless value[:flag].is_a?(Integer)
272
+ raise UsageError, "#{path}: the CAA flag is a whole number, got #{value[:flag].inspect}"
273
+ end
274
+ tag = value[:tag].is_a?(Symbol) ? value[:tag].name : value[:tag]
275
+ unless tag.is_a?(String) && CAA_TAGS.value?(tag)
276
+ raise UsageError, "#{path}: the CAA tag takes #{CAA_TAGS.keys.map(&:inspect).join(", ")}, got #{value[:tag].inspect}"
277
+ end
278
+ unless value[:value].is_a?(String) && !value[:value].empty?
279
+ raise UsageError, "#{path}: the CAA value is a String, got #{value[:value].inspect}"
280
+ end
281
+
282
+ "#{value[:flag]} #{tag} \"#{value[:value]}\""
283
+ end
284
+ end
285
+
286
+ # The Amazon CAA record: the CDK's CaaAmazonRecord
287
+ # (record-set.ts:915-933), a CaaRecord of the one value that restricts
288
+ # certificate authorities for the zone to Amazon only.
289
+ class CaaAmazonRecord < CaaRecord
290
+ def initialize(zone, id, record_name: nil, ttl: nil, comment: nil)
291
+ super(zone, id, values: [ { flag: 0, tag: "issue", value: "amazon.com" } ],
292
+ record_name:, ttl:, comment:)
293
+ end
294
+ end
295
+
296
+ # The DNS MX record: the CDK's MxRecord (record-set.ts:966-979). Each
297
+ # value is a Hash { priority:, host_name: }, rendered as the two
298
+ # space-separated fields.
299
+ class MxRecord < RecordSet
300
+ def initialize(zone, id, values:, record_name: nil, ttl: nil, comment: nil)
301
+ super(zone, id, record_type: "MX", values: values.map { |value| mx_value(value) },
302
+ record_name:, ttl:, comment:)
303
+ end
304
+
305
+ private
306
+
307
+ def mx_value(value)
308
+ unless value.is_a?(Hash) && (%i[priority host_name] - value.keys).empty?
309
+ raise UsageError, "#{path}: each MX value is a Hash { priority:, host_name: }, got #{value.inspect}"
310
+ end
311
+ unless value[:priority].is_a?(Integer)
312
+ raise UsageError, "#{path}: the MX priority is a whole number, got #{value[:priority].inspect}"
313
+ end
314
+ unless value[:host_name].is_a?(String) && !value[:host_name].empty?
315
+ raise UsageError, "#{path}: the MX host_name is a String, got #{value[:host_name].inspect}"
316
+ end
317
+
318
+ "#{value[:priority]} #{value[:host_name]}"
319
+ end
320
+ end
321
+
322
+ # The DNS NS record: the CDK's NsRecord (record-set.ts:997-1010), the
323
+ # values the name server names.
324
+ class NsRecord < RecordSet
325
+ def initialize(zone, id, values:, record_name: nil, ttl: nil, comment: nil)
326
+ super(zone, id, record_type: "NS", values:, record_name:, ttl:, comment:)
327
+ end
328
+ end
329
+ end
330
+ end