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,822 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "../errors"
5
+ require_relative "../fn"
6
+ require_relative "../core/context"
7
+ require_relative "vpc_network"
8
+
9
+ module RubyCdk
10
+ module EC2
11
+ # A VPC: the port of the CDK's Vpc (aws-ec2/lib/vpc.ts), read at commit
12
+ # c070afb54b9e4dbddd52a85a21077fe970354985, Apache-2.0. This is the
13
+ # defaults slice: the VPC itself, the Internet Gateway and its attachment,
14
+ # the subnets across availability zones with their route tables and
15
+ # routes, and the NAT gateways of the CDK's default behaviour.
16
+ #
17
+ # RubyCdk::EC2::Vpc.new(stack, "Vpc")
18
+ # RubyCdk::EC2::Vpc.new(stack, "Vpc",
19
+ # max_azs: 2, subnet_configuration: [
20
+ # { name: "ingress", subnet_type: :public, cidr_mask: 24 },
21
+ # { name: "application", subnet_type: :private_with_egress, cidr_mask: 24 }
22
+ # ])
23
+ #
24
+ # The defaults are the CDK's (vpc.ts:1588-1829): the CIDR is
25
+ # DEFAULT_CIDR_RANGE, 10.0.0.0/16 (vpc.ts:1344), DNS support and DNS
26
+ # hostnames are on (vpc.ts:1630-1631) and the instance tenancy "default"
27
+ # (vpc.ts:1632); the AWS::EC2::VPC is written with all four stated
28
+ # (vpc.ts:1638-1645). The subnet configuration defaults to one public and
29
+ # one private subnet per availability zone (vpc.ts:1351-1360), evenly
30
+ # split across the CIDR (ip-addresses.ts:391-414: the subnets without a
31
+ # cidrMask share what is left, which for the default is /19 each), and to
32
+ # one public and one isolated subnet per zone when nat_gateways is 0
33
+ # (vpc.ts:1363-1376). An Internet Gateway and its attachment are created
34
+ # when any subnet can reach the internet (vpc.ts:1735-1750), each public
35
+ # subnet takes a 0.0.0.0/0 route to the gateway, dependent on the
36
+ # attachment (vpc.ts:2348-2359), and a NAT Gateway plus its EIP is built
37
+ # in every public subnet - one per zone, unless nat_gateways: lowers the
38
+ # count - with every private subnet routed to the gateway of its own zone
39
+ # when there is one, and to the gateways in turn otherwise
40
+ # (nat.ts:413-445, the PrefSet's round-robin at nat.ts:710-735). Each
41
+ # subnet carries its own route table and its SubnetRouteTableAssociation
42
+ # (vpc.ts:2325-2334). Reserved subnet configurations hold their CIDR
43
+ # space but build nothing (vpc.ts:1977-1988).
44
+ #
45
+ # The availability zones are the ones given in availability_zones:, or
46
+ # the first max_azs of the three names the CDK's synthesis resolves to
47
+ # when its context cache is empty - "dummy1a", "dummy1b", "dummy1c"
48
+ # (core/lib/stack.ts:937-950, availabilityZones' dummyValue). The created
49
+ # path reads no context (D-022): pass availability_zones: with real zone
50
+ # names to write them into the subnets, or take the lookups of
51
+ # from_lookup below. max_azs defaults to 3 (vpc.ts:1665); both options
52
+ # together are refused, as the CDK refuses them (vpc.ts:1600-1601). A
53
+ # negative max_azs or nat_gateways is refused: the CDK's slice would read
54
+ # it as a count from the end, which is the language's answer, not a rule.
55
+ #
56
+ # Where this tool differs from the CDK (architecture section 7 wins; the
57
+ # rows are in section 21):
58
+ #
59
+ # - restrict_default_security_group: false is accepted and changes
60
+ # nothing: this VPC is built without the restriction, which is what
61
+ # the option asks for. true is refused: the CDK writes a
62
+ # Lambda-backed Custom::VpcRestrictDefaultSG custom resource that
63
+ # revokes the default security group's rules at deploy time
64
+ # (vpc.ts:2039-2068), and this tool has no custom resources and ships
65
+ # no process. The CDK's feature flag defaults to on
66
+ # (cx-api/lib/features.ts:864-875, recommendedValue true), so a CDK
67
+ # Vpc carries that resource by default and a Vpc here does not.
68
+ # - The Name tag of the VPC and the Name and
69
+ # aws-cdk:subnet-name/aws-cdk:subnet-type tags of the subnets
70
+ # (vpc.ts:1653, 2034-2035) are not written: this tool has no tag
71
+ # aspect.
72
+ #
73
+ # Options carried: cidr:, max_azs:, availability_zones:, dns_support:,
74
+ # dns_hostnames:, default_instance_tenancy:, subnet_configuration: (the
75
+ # CDK's SubnetConfiguration: name, subnet_type, cidr_mask, reserved,
76
+ # map_public_ip_on_launch - the deprecated subnet type names :private,
77
+ # :private_with_nat and :isolated behave as their replacements, as the
78
+ # CDK's aliases do), nat_gateways: and nat_gateway_subnets: (a placement
79
+ # by group name, name:, or by type, subnet_type:, the CDK's
80
+ # SubnetSelection; the default places the gateways in the public subnets,
81
+ # vpc.ts:1687). The types are :public, :private_with_egress and
82
+ # :private_isolated; a public subnet takes map_public_ip_on_launch,
83
+ # defaulting to true (vpc.ts:1964-1968), and a private or isolated one
84
+ # refuses it, as the CDK refuses it (vpc.ts:1970-1972) - unless the
85
+ # configuration is reserved, which the CDK skips before the check runs
86
+ # (vpc.ts:1981-1984).
87
+ #
88
+ # Not carried, each a row for section 21: VPC endpoints, flow logs, the
89
+ # VPN gateway and connections, IPAM (ipAddresses: and the ipv4 fields),
90
+ # the IPv6 protocol and its fields, reserved_azs:,
91
+ # create_internet_gateway:, vpc_name: (the Name tag behind it), the NAT
92
+ # providers beyond the gateway one (natGatewayProvider: instances,
93
+ # regional gateways and given EIP allocation ids), the standalone
94
+ # PublicSubnet/PrivateSubnet constructs, addRoute/addNatGateway on
95
+ # subnets, the lookup options beyond vpc_id: and tags: (vpcName,
96
+ # isDefault, ownerAccountId, region, returnVpnGateways,
97
+ # subnetGroupNameTag), and fromVpcAttributes: an import whose values are
98
+ # given by hand is written as the literals they already are.
99
+ #
100
+ # Net = RubyCdk::EC2::Vpc.from_lookup(stack, "Net", vpc_id: "vpc-0abc1234")
101
+ #
102
+ # from_lookup is the CDK's fromLookup (vpc.ts:1410-1452) as decision
103
+ # D-022 shapes it: the answer is read from the context cache
104
+ # cdk.context.json beside the app file, which `ruby-cdk lookup` writes
105
+ # and synth only reads. A looked-up VPC synthesizes no resources (the
106
+ # CDK's LookedUpVpc, vpc.ts:2745-2820): the VPC, its subnets and their
107
+ # route tables already exist, and creating them again would not be an
108
+ # import. What the construct answers are the literals the cache holds -
109
+ # the vpc id, its CIDR, the zone names, the subnet ids grouped by
110
+ # reachability type - so a consumer of the VPC synthesizes the same
111
+ # resources it would with a created one, with no Fn::GetAtt and no
112
+ # Fn::ImportValue anywhere. On a cache miss from_lookup raises the error
113
+ # that names `ruby-cdk lookup`; it never calls AWS. The query needs the
114
+ # stack's concrete env, as the CDK needs a concrete account and region
115
+ # for a context lookup (context-provider.ts:167-172): the cache key
116
+ # carries them, and an answer is never read for the wrong environment.
117
+ class Vpc < Construct
118
+ # The default CIDR range (vpc.ts:1344).
119
+ DEFAULT_CIDR_RANGE = "10.0.0.0/16"
120
+
121
+ # The default availability-zone count (vpc.ts:1665), and the three
122
+ # zone names the CDK's synthesis resolves to without context
123
+ # (core/lib/stack.ts:950, availabilityZones' dummyValue).
124
+ DEFAULT_MAX_AZS = 3
125
+ AZ_DUMMY_NAMES = %w[ dummy1a dummy1b dummy1c ].freeze
126
+
127
+ # The default subnet configuration, and the one nat_gateways: 0 picks
128
+ # (vpc.ts:1351-1376). The names are the CDK's defaultSubnetName
129
+ # (util.ts:19-30), and they name the subnet groups a NAT placement
130
+ # selects by.
131
+ DEFAULT_SUBNETS = [
132
+ { name: "Public", subnet_type: :public },
133
+ { name: "Private", subnet_type: :private_with_egress }
134
+ ].freeze
135
+ DEFAULT_SUBNETS_NO_NAT = [
136
+ { name: "Public", subnet_type: :public },
137
+ { name: "Isolated", subnet_type: :private_isolated }
138
+ ].freeze
139
+
140
+ # The CDK's SubnetType (vpc.ts:252-348): the name each value carries,
141
+ # and the value each deprecated alias stands for. The name is what the
142
+ # refusals quote.
143
+ SUBNET_TYPE_NAMES = {
144
+ public: "Public",
145
+ private_with_egress: "Private",
146
+ private_isolated: "Isolated",
147
+ private: "Private",
148
+ private_with_nat: "Private",
149
+ isolated: "Isolated"
150
+ }.freeze
151
+
152
+ # The types that route through a NAT gateway and the ones that do not,
153
+ # as determineNatGatewayCount counts them (vpc.ts:2960-2963).
154
+ PRIVATE_TYPES = %i[private_with_egress private private_with_nat].freeze
155
+ PUBLIC_TYPES = %i[public].freeze
156
+ ISOLATED_TYPES = %i[private_isolated isolated].freeze
157
+
158
+ # The instance tenancies (vpc.ts:1632, the DefaultInstanceTenancy
159
+ # values).
160
+ INSTANCE_TENANCIES = %w[default dedicated].freeze
161
+
162
+ # The destination of the default routes (vpc.ts:2351, 2452).
163
+ DEFAULT_ROUTE_CIDR = "0.0.0.0/0"
164
+
165
+ # The provider name in the context cache (the CDK's VPC_PROVIDER,
166
+ # cxschema.ContextProvider.VPC_PROVIDER). The key of one answer is
167
+ # "vpc:account=...:region=...:..." (Core::Context.key).
168
+ PROVIDER = "vpc"
169
+
170
+ attr_reader :azs, :dns_support_enabled, :dns_hostnames_enabled
171
+
172
+ def initialize(scope, id, cidr: nil, max_azs: nil, availability_zones: nil, nat_gateways: nil,
173
+ nat_gateway_subnets: nil, subnet_configuration: nil, default_instance_tenancy: nil,
174
+ restrict_default_security_group: nil, dns_support: nil, dns_hostnames: nil)
175
+ super(scope, id)
176
+ if dns_hostnames == true && dns_support == false
177
+ raise UsageError, "#{path}: To use DNS Hostnames, DNS Support must be enabled, " \
178
+ "however, it was explicitly disabled."
179
+ end
180
+ if availability_zones && max_azs
181
+ raise UsageError, "#{path}: Vpc supports 'availability_zones' or 'max_azs', but not both."
182
+ end
183
+
184
+ @cidr = cidr || DEFAULT_CIDR_RANGE
185
+ raise_cidr_concrete unless @cidr.is_a?(String)
186
+ @dns_hostnames_enabled = dns_hostnames.nil? ? true : flag(dns_hostnames, "dns_hostnames")
187
+ @dns_support_enabled = dns_support.nil? ? true : flag(dns_support, "dns_support")
188
+ @tenancy = tenancy(default_instance_tenancy)
189
+ @azs = resolve_azs(availability_zones, max_azs)
190
+ restrict(restrict_default_security_group)
191
+
192
+ # The VPC itself (vpc.ts:1638-1645).
193
+ @resource = resource("Resource", "AWS::EC2::VPC",
194
+ CidrBlock: @cidr,
195
+ EnableDnsHostnames: @dns_hostnames_enabled,
196
+ EnableDnsSupport: @dns_support_enabled,
197
+ InstanceTenancy: @tenancy)
198
+
199
+ @configs = subnet_configuration(subnet_configuration, nat_gateways)
200
+ @nat_count = nat_gateway_count(nat_gateways)
201
+ @public_subnets = []
202
+ @private_subnets = []
203
+ @isolated_subnets = []
204
+
205
+ create_subnets
206
+ return unless outbound?
207
+
208
+ # The gateway and its attachment (vpc.ts:1740-1750). The CDK's
209
+ # createInternetGateway: false turns these off; the option is a
210
+ # section 21 row, not carried.
211
+ @igw = resource("IGW", "AWS::EC2::InternetGateway")
212
+ @attachment = resource("VPCGW", "AWS::EC2::VPCGatewayAttachment",
213
+ InternetGatewayId: Fn.ref(@igw),
214
+ VpcId: Fn.ref(@resource))
215
+ @public_subnets.each { |subnet| default_internet_route(subnet) }
216
+ create_nat_gateways(nat_gateway_subnets)
217
+ end
218
+
219
+ # The logical ID of the AWS::EC2::VPC under this construct, so that the
220
+ # VPC can sit in another resource's depends_on:.
221
+ def logical_id
222
+ @resource.logical_id
223
+ end
224
+
225
+ # The ID of the VPC: the Ref of the resource (vpc.ts:1677).
226
+ def vpc_id
227
+ Fn.ref(@resource)
228
+ end
229
+
230
+ # The VPC's ARN, over the pseudo parameters, as the CDK's Arn.format of
231
+ # the Ref (vpc.ts:1678-1682) renders in a stack without a concrete env.
232
+ def vpc_arn
233
+ Fn.sub("arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:vpc/${VpcId}",
234
+ "VpcId" => vpc_id)
235
+ end
236
+
237
+ # The VPC's IPv4 CIDR: the Fn::GetAtt of the resource (vpc.ts:1649).
238
+ def vpc_cidr_block
239
+ Fn.get_att(@resource, "CidrBlock")
240
+ end
241
+
242
+ # The ID of the default network ACL (vpc.ts:1647) and of the default
243
+ # security group (vpc.ts:1650), the two attributes the constructs that
244
+ # reference a VPC read.
245
+ def vpc_default_network_acl
246
+ Fn.get_att(@resource, "DefaultNetworkAcl")
247
+ end
248
+
249
+ def vpc_default_security_group
250
+ Fn.get_att(@resource, "DefaultSecurityGroup")
251
+ end
252
+
253
+ # The ID of the Internet Gateway, or nil when no subnet reaches the
254
+ # internet and none was built (vpc.ts:1517-1520).
255
+ def internet_gateway_id
256
+ @igw && Fn.ref(@igw)
257
+ end
258
+
259
+ # The subnet IDs, each the Ref of its AWS::EC2::Subnet, in zone order:
260
+ # the CDK's publicSubnets, privateSubnets and isolatedSubnets
261
+ # (vpc.ts:1499-1509).
262
+ def public_subnet_ids
263
+ @public_subnets.map { |subnet| Fn.ref(subnet[:resource]) }
264
+ end
265
+
266
+ def private_subnet_ids
267
+ @private_subnets.map { |subnet| Fn.ref(subnet[:resource]) }
268
+ end
269
+
270
+ def isolated_subnet_ids
271
+ @isolated_subnets.map { |subnet| Fn.ref(subnet[:resource]) }
272
+ end
273
+
274
+ # Imports an existing VPC whose answer the context cache beside the
275
+ # app file already holds. The query is vpc_id: (a concrete id, or nil)
276
+ # plus tags: (which the VPC must all carry); with neither, the account
277
+ # and region must hold exactly one VPC. All arguments must be
278
+ # concrete: the CDK refuses tokens here
279
+ # ("All arguments to Vpc.fromLookup() must be concrete (no Tokens)",
280
+ # vpc.ts:1414-1416), and this tool has no tokens to write anyway. The
281
+ # stack needs a concrete env: the answer is cached per account and
282
+ # region, so a lookup without one could not name its cache entry - the
283
+ # CDK's refusal at context-provider.ts:167-172. A miss raises the
284
+ # error that names `ruby-cdk lookup`; this path never calls AWS.
285
+ def self.from_lookup(scope, id, vpc_id: nil, tags: nil)
286
+ LookedUp.import(scope, id, vpc_id: vpc_id, tags: tags)
287
+ end
288
+
289
+ private
290
+
291
+ def flag(value, what)
292
+ return value if value == true || value == false
293
+
294
+ raise UsageError, "#{path}: #{what} takes true or false, got #{value.inspect}"
295
+ end
296
+
297
+ # vpc.ts:1605-1607: the subdivision parses the CIDR, so it has to be
298
+ # concrete.
299
+ def raise_cidr_concrete
300
+ what = @cidr.is_a?(Hash) ? "a Token" : @cidr.inspect
301
+ raise UsageError, "#{path}: 'cidr' property must be a concrete CIDR string, got #{what} " \
302
+ "(we need to parse it for automatic subdivision)"
303
+ end
304
+
305
+ def tenancy(value)
306
+ return "default" if value.nil?
307
+
308
+ name = value.is_a?(Symbol) ? value.name : value
309
+ return name if name.is_a?(String) && INSTANCE_TENANCIES.include?(name)
310
+
311
+ raise UsageError, "#{path}: default_instance_tenancy takes :default or :dedicated, got #{value.inspect}"
312
+ end
313
+
314
+ # The availability zones: the ones given, or the first max_azs of the
315
+ # dummy trio (vpc.ts:1655-1667; the context's dummyValue at
316
+ # core/lib/stack.ts:950).
317
+ def resolve_azs(zones, max_azs)
318
+ return given_zones(zones) if zones
319
+
320
+ AZ_DUMMY_NAMES.first(zone_count(max_azs))
321
+ end
322
+
323
+ def given_zones(zones)
324
+ unless zones.is_a?(Array) && zones.all? { |zone| zone.is_a?(String) && !zone.empty? }
325
+ raise UsageError, "#{path}: availability_zones takes non-empty String zone names, got #{zones.inspect}"
326
+ end
327
+
328
+ zones
329
+ end
330
+
331
+ def zone_count(max_azs)
332
+ return DEFAULT_MAX_AZS if max_azs.nil?
333
+ return max_azs if max_azs.is_a?(Integer) && max_azs >= 0
334
+
335
+ raise UsageError, "#{path}: max_azs takes a whole number of zones, got #{max_azs.inspect}"
336
+ end
337
+
338
+ # The option as the CDK's flag reads it: false is the behaviour this
339
+ # tool already has; true needs the Lambda custom resource this tool
340
+ # cannot build.
341
+ def restrict(value)
342
+ return nil if value.nil?
343
+ return false if value == false
344
+
345
+ raise UsageError, "#{path}: restrict_default_security_group takes false; true writes the CDK's " \
346
+ "Custom::VpcRestrictDefaultSG custom resource (vpc.ts:2039-2068), and this tool has no custom resources. " \
347
+ "Revoke the default security group's rules outside this construct"
348
+ end
349
+
350
+ # The configurations as they travel: one Hash per entry, in the CDK's
351
+ # field order, with only what was given. The default is the CDK's
352
+ # DEFAULT_SUBNETS, or DEFAULT_SUBNETS_NO_NAT for nat_gateways: 0
353
+ # (vpc.ts:1684-1685).
354
+ def subnet_configuration(configuration, nat_gateways)
355
+ entries = configuration || (nat_gateways == 0 ? DEFAULT_SUBNETS_NO_NAT : DEFAULT_SUBNETS)
356
+ unless entries.is_a?(Array) && !entries.empty?
357
+ raise UsageError, "#{path}: subnet_configuration takes a non-empty Array of Hashes, got #{entries.inspect}"
358
+ end
359
+
360
+ entries.map { |entry| valid_config(entry) }
361
+ end
362
+
363
+ def valid_config(entry)
364
+ unless entry.is_a?(Hash)
365
+ raise UsageError, "#{path}: each subnet_configuration entry is a Hash, got #{entry.inspect}"
366
+ end
367
+
368
+ type = valid_type(entry)
369
+ name = entry[:name]
370
+ unless name.is_a?(String) && !name.empty?
371
+ raise UsageError, "#{path}: each subnet_configuration entry takes a name String, got #{name.inspect}"
372
+ end
373
+ mask = entry[:cidr_mask]
374
+ if mask && !(mask.is_a?(Integer) && mask >= 16 && mask <= 28)
375
+ raise UsageError, "#{path}: #{name.inspect}: x.x.x.x/#{mask}#{CidrBlock::INVALID_RANGE_SUFFIX}"
376
+ end
377
+ reserved = flag_or_nil(entry[:reserved], "reserved", name)
378
+ on_launch = flag_or_nil(entry[:map_public_ip_on_launch], "map_public_ip_on_launch", name)
379
+ unless type == :public || on_launch.nil? || reserved == true
380
+ raise UsageError, "#{path}: #{SUBNET_TYPE_NAMES.fetch(type)} subnet cannot include " \
381
+ "map_public_ip_on_launch parameter"
382
+ end
383
+
384
+ # The fields of the CDK's SubnetConfiguration, in its order, so that
385
+ # the refusal that quotes a configuration as JSON quotes it as the
386
+ # CDK does (vpc.ts:2972).
387
+ config = { subnet_type: type, name: name }
388
+ config[:cidr_mask] = mask if mask
389
+ config[:reserved] = reserved unless reserved.nil?
390
+ config[:map_public_ip_on_launch] = on_launch unless on_launch.nil?
391
+ config
392
+ end
393
+
394
+ def flag_or_nil(value, what, name)
395
+ return nil if value.nil?
396
+ return value if value == true || value == false
397
+
398
+ raise UsageError, "#{path}: the #{what} of #{name.inspect} takes true or false, got #{value.inspect}"
399
+ end
400
+
401
+ def valid_type(entry)
402
+ type = entry[:subnet_type]
403
+ return type if type.is_a?(Symbol) && SUBNET_TYPE_NAMES.key?(type)
404
+
405
+ raise UsageError, "#{path}: each subnet_configuration entry takes a subnet_type of " \
406
+ "#{SUBNET_TYPE_NAMES.keys.uniq.join(", ")}, got #{type.inspect}"
407
+ end
408
+
409
+ # The port of determineNatGatewayCount (vpc.ts:2946-2976): the count
410
+ # given, at most one per zone; without one, one per zone when a private
411
+ # subnet is configured and none otherwise. Zero gateways over a private
412
+ # subnet that is not a PRIVATE_WITH_EGRESS one is refused, as is a
413
+ # gateway count over a configuration with no public subnet - both in
414
+ # the CDK's words (vpc.ts:2967-2973).
415
+ def nat_gateway_count(requested)
416
+ if requested && !(requested.is_a?(Integer) && requested >= 0)
417
+ raise UsageError, "#{path}: nat_gateways takes a whole number of gateways, got #{requested.inspect}"
418
+ end
419
+
420
+ has_private = @configs.any? { |config| PRIVATE_TYPES.include?(config[:subnet_type]) && !config[:reserved] }
421
+ has_egress = @configs.any? { |config| config[:subnet_type] == :private_with_egress }
422
+ has_public = @configs.any? { |config| PUBLIC_TYPES.include?(config[:subnet_type]) && !config[:reserved] }
423
+ count = requested || (has_private ? @azs.length : 0)
424
+
425
+ if count.zero? && has_private && !has_egress
426
+ raise UsageError, "#{path}: If you do not want NAT gateways (natGateways=0), make sure you don't configure " \
427
+ "any PRIVATE(_WITH_NAT) subnets in 'subnetConfiguration' (make them PUBLIC or ISOLATED instead)"
428
+ end
429
+ if count.positive? && !has_public
430
+ raise UsageError, "#{path}: If you configure PRIVATE subnets in 'subnetConfiguration', you must also " \
431
+ "configure PUBLIC subnets to put the NAT gateways into (got #{JSON.generate(configs_as_json)})."
432
+ end
433
+
434
+ [ count, @azs.length ].min
435
+ end
436
+
437
+ # The configurations as the CDK's JSON.stringify of the props objects
438
+ # writes them (vpc.ts:2972): the fields given, the CDK's names.
439
+ def configs_as_json
440
+ @configs.map do |config|
441
+ json = { "subnetType" => SUBNET_TYPE_NAMES.fetch(config[:subnet_type]), "name" => config[:name] }
442
+ json["cidrMask"] = config[:cidr_mask] if config[:cidr_mask]
443
+ json["reserved"] = config[:reserved] unless config[:reserved].nil?
444
+ json
445
+ end
446
+ end
447
+
448
+ # Any subnet that can reach the internet, directly or through a NAT
449
+ # gateway, needs the gateway and its attachment (vpc.ts:1736-1740): an
450
+ # isolated or reserved configuration does not count.
451
+ def outbound?
452
+ @configs.any? do |config|
453
+ !ISOLATED_TYPES.include?(config[:subnet_type]) && !config[:reserved]
454
+ end
455
+ end
456
+
457
+ # createSubnets (vpc.ts:1890-1901): one subnet construct per
458
+ # configuration per zone, the id the CDK's subnetId builds
459
+ # (util.ts:44-46, "NameSubnetN"), and its CIDR from the allocation
460
+ # (ip-addresses.ts:391-414). Reserved configurations consume their
461
+ # CIDR and build nothing (vpc.ts:1977-1988).
462
+ def create_subnets
463
+ requested = @configs.flat_map { |config| @azs.each_index.map { |index| [ config, index ] } }
464
+ cidrs = allocate(requested.length, requested.map { |config, _| config[:cidr_mask] })
465
+
466
+ requested.each_with_index do |(config, index), i|
467
+ next if config[:reserved]
468
+
469
+ parent = Construct.new(self, subnet_id(config[:name], index))
470
+ subnet = build_subnet(parent, config, cidrs[i], @azs[index])
471
+ case config[:subnet_type]
472
+ when :public then @public_subnets << subnet
473
+ when *PRIVATE_TYPES then @private_subnets << subnet
474
+ else @isolated_subnets << subnet
475
+ end
476
+ end
477
+ end
478
+
479
+ # The CDK's Cidr allocation (ip-addresses.ts:391-414): the
480
+ # configurations with a cidrMask carve theirs first, in order, then the
481
+ # rest share the remaining space evenly.
482
+ def allocate(count, masks)
483
+ builder = NetworkBuilder.new(@cidr)
484
+ cidrs = Array.new(count)
485
+ without = []
486
+ masks.each_with_index do |mask, index|
487
+ if mask
488
+ cidrs[index] = builder.add_subnet(mask)
489
+ else
490
+ without << index
491
+ end
492
+ end
493
+ remaining_mask = builder.mask_for_remaining_subnets(without.length)
494
+ without.each { |index| cidrs[index] = builder.add_subnet(remaining_mask) }
495
+ cidrs
496
+ end
497
+
498
+ # subnetId (util.ts:44-46): "NameSubnetN", N from one.
499
+ def subnet_id(name, index)
500
+ "#{name}Subnet#{index + 1}"
501
+ end
502
+
503
+ # The resources of one subnet (vpc.ts:2299-2334): the
504
+ # AWS::EC2::Subnet, its route table, and the association between them.
505
+ def build_subnet(parent, config, cidr, az)
506
+ subnet_resource = parent.resource("Subnet", "AWS::EC2::Subnet",
507
+ VpcId: Fn.ref(@resource),
508
+ CidrBlock: cidr,
509
+ AvailabilityZone: az,
510
+ MapPublicIpOnLaunch: map_public_ip_on_launch(config))
511
+ table = parent.resource("RouteTable", "AWS::EC2::RouteTable", VpcId: Fn.ref(@resource))
512
+ assoc = parent.resource("RouteTableAssociation", "AWS::EC2::SubnetRouteTableAssociation",
513
+ SubnetId: Fn.ref(subnet_resource),
514
+ RouteTableId: Fn.ref(table))
515
+ { config:, resource: subnet_resource, table:, assoc:, parent:, az: }
516
+ end
517
+
518
+ # calculateMapPublicIpOnLaunch (vpc.ts:1964-1975): true in a public
519
+ # subnet unless the configuration says otherwise, false in any other.
520
+ def map_public_ip_on_launch(config)
521
+ if config[:subnet_type] == :public
522
+ config.fetch(:map_public_ip_on_launch, true)
523
+ else
524
+ false
525
+ end
526
+ end
527
+
528
+ # The public subnet's route to the gateway, with the dependency on the
529
+ # attachment the CDK adds (vpc.ts:2348-2359).
530
+ def default_internet_route(subnet)
531
+ route = subnet[:parent].resource("DefaultRoute", "AWS::EC2::Route",
532
+ RouteTableId: Fn.ref(subnet[:table]),
533
+ DestinationCidrBlock: DEFAULT_ROUTE_CIDR,
534
+ GatewayId: Fn.ref(@igw),
535
+ depends_on: [ @attachment ])
536
+ subnet[:route] = route
537
+ end
538
+
539
+ # The NAT gateways (vpc.ts:1860-1884, nat.ts:413-435): the placement
540
+ # selects the subnets, the first @nat_count of them each take an EIP
541
+ # and a NAT Gateway that depends on its subnet's association and route
542
+ # (vpc.ts:2642-2653), and every private subnet takes a 0.0.0.0/0 route
543
+ # to the gateway of its own zone, or to the gateways in turn
544
+ # (nat.ts:437-445, PrefSet.pick's round-robin at nat.ts:722-729). With
545
+ # no gateway there is no route: the CDK's configureNat runs only for a
546
+ # positive count (vpc.ts:1764-1767).
547
+ def create_nat_gateways(placement)
548
+ return if @nat_count.zero?
549
+
550
+ nat_subnets = placement_subnets(placement).first(@nat_count)
551
+ gateways = []
552
+ nat_subnets.each do |subnet|
553
+ eip = subnet[:parent].resource("EIP", "AWS::EC2::EIP", Domain: "vpc")
554
+ gateway = subnet[:parent].resource("NATGateway", "AWS::EC2::NatGateway",
555
+ SubnetId: Fn.ref(subnet[:resource]),
556
+ AllocationId: Fn.get_att(eip, "AllocationId"),
557
+ depends_on: [ subnet[:assoc], subnet[:route] ])
558
+ gateways << { az: subnet[:az], resource: gateway }
559
+ end
560
+
561
+ next_pick = 0
562
+ @private_subnets.each do |subnet|
563
+ gateway, used_fallback = pick_gateway(gateways, subnet[:az], next_pick)
564
+ next_pick += 1 if used_fallback
565
+ subnet[:parent].resource("DefaultRoute", "AWS::EC2::Route",
566
+ RouteTableId: Fn.ref(subnet[:table]),
567
+ DestinationCidrBlock: DEFAULT_ROUTE_CIDR,
568
+ NatGatewayId: Fn.ref(gateway))
569
+ end
570
+ end
571
+
572
+ # PrefSet.pick (nat.ts:722-729): the gateway of the zone when there is
573
+ # one; otherwise the gateways in turn, and only a fallback pick
574
+ # advances the rotation.
575
+ def pick_gateway(gateways, az, fallback_index)
576
+ own = gateways.find { |gateway| gateway[:az] == az }
577
+ return [ own[:resource], false ] if own
578
+
579
+ [ gateways[fallback_index % gateways.length][:resource], true ]
580
+ end
581
+
582
+ # The placement (vpc.ts:1687, selectSubnetObjects at vpc.ts:663-692):
583
+ # by group name or by type, over all the VPC's subnets, the public type
584
+ # the default. A name with no group is the CDK's refusal, in its words
585
+ # (vpc.ts:694-705); a selected group that is not public is refused, as
586
+ # createNatGateways refuses it (vpc.ts:1871-1876).
587
+ def placement_subnets(placement)
588
+ placement ||= { subnet_type: :public }
589
+ unless placement.is_a?(Hash) && (placement.keys - %i[name subnet_type]).empty? &&
590
+ (placement.key?(:name) ^ placement.key?(:subnet_type))
591
+ raise UsageError, "#{path}: nat_gateway_subnets takes name: or subnet_type:, got #{placement.inspect}"
592
+ end
593
+
594
+ if placement[:name]
595
+ named = (@public_subnets + @private_subnets + @isolated_subnets)
596
+ .select { |subnet| group_of(subnet) == placement[:name] }
597
+ if named.empty?
598
+ names = (@public_subnets + @private_subnets + @isolated_subnets)
599
+ .map { |subnet| group_of(subnet) }.uniq
600
+ raise UsageError, "#{path}: There are no subnet groups with name '#{placement[:name]}' in this VPC. " \
601
+ "Available names: #{names.join(",")}"
602
+ end
603
+ unless named.all? { |subnet| PUBLIC_TYPES.include?(subnet[:config][:subnet_type]) }
604
+ raise UsageError, "#{path}: nat_gateway_subnets #{placement.inspect} contains non public subnet"
605
+ end
606
+
607
+ named
608
+ else
609
+ type = placement.fetch(:subnet_type, :public)
610
+ unless PUBLIC_TYPES.include?(type)
611
+ raise UsageError, "#{path}: nat_gateway_subnets takes the subnet_type :public, got #{type.inspect}"
612
+ end
613
+
614
+ @public_subnets
615
+ end
616
+ end
617
+
618
+ # subnetGroupNameFromConstructId (util.ts:37-39): the configuration
619
+ # name behind the subnet's construct id.
620
+ def group_of(subnet)
621
+ subnet[:config][:name]
622
+ end
623
+ end
624
+
625
+ # The looked-up VPC (the CDK's LookedUpVpc, vpc.ts:2745-2820, reached
626
+ # through Vpc.from_lookup): a tree node that synthesizes no resources.
627
+ # The VPC, its subnets and their route tables already exist, and creating
628
+ # them again would not be an import; what the construct answers are the
629
+ # literals the cache holds, so a consumer synthesizes the same resources
630
+ # it would with a created Vpc, with no Fn::GetAtt and no Fn::ImportValue
631
+ # anywhere. The attributes the created Vpc reads off its own resources -
632
+ # the logical ID, the default network ACL and security group - are
633
+ # refused here: nothing of this stack carries them, and the CDK's lookup
634
+ # answer does not name them either. The internet gateway id is nil, as
635
+ # the CDK's LookedUpVpc leaves it unset, and the two dns flags are nil:
636
+ # the answer does not say.
637
+ class Vpc
638
+ class LookedUp < Construct
639
+ # The reachability types of the answer, and the group name each one
640
+ # answers to, the CDK's default subnet names. The adapter writes
641
+ # them (Deploy::Sdk::Ec2Client); they are named here and not read
642
+ # from there, because the constructs do not depend on the adapters.
643
+ LOOKUP_TYPES = {
644
+ "public" => "Public",
645
+ "private" => "Private",
646
+ "isolated" => "Isolated"
647
+ }.freeze
648
+
649
+ # The nearest Stack carries the env the query is cached under.
650
+ def self.import(scope, id, vpc_id: nil, tags: nil)
651
+ stack = lookup_stack(scope, id)
652
+ unless stack.env
653
+ raise UsageError, "#{stack.path}: Cannot retrieve value from context provider " \
654
+ "#{PROVIDER} since account/region are not specified at the stack level. " \
655
+ "Configure \"env\" with an account and region when you define your stack."
656
+ end
657
+ query = Context::Query.new(provider: PROVIDER, account: stack.env.account, region: stack.env.region,
658
+ args: lookup_args(id, scope, vpc_id, tags))
659
+ cache = stack.app.context_file
660
+ unless cache
661
+ raise UsageError, "#{stack.path}: the App has no context cache to read: an App built from an app " \
662
+ "file reads #{Context::FILE_NAME} from the file's directory. Run the command from the app's " \
663
+ "directory, or build the App with App.build!."
664
+ end
665
+
666
+ where = "the Vpc #{id.inspect} of the stack #{stack.stack_name.inspect}"
667
+ answer = validate_answer(Context.answer(cache, query, where: where), cache, query)
668
+ new(scope, id, answer)
669
+ end
670
+
671
+ # Every attribute answers the literal of the answer.
672
+ def initialize(scope, id, answer)
673
+ super(scope, id)
674
+ @answer = answer
675
+ @azs = answer.fetch("availability_zones")
676
+ @public_subnets = subnets_of("public")
677
+ @private_subnets = subnets_of("private")
678
+ @isolated_subnets = subnets_of("isolated")
679
+ end
680
+
681
+ # The zones of the VPC's subnets, as the answer holds them: sorted,
682
+ # without duplicates, as the lookup provider writes them.
683
+ attr_reader :azs
684
+
685
+ def vpc_id
686
+ @answer.fetch("vpc_id")
687
+ end
688
+
689
+ # Over the pseudo parameters, as the created Vpc answers it: the id
690
+ # is literal, and the environment CloudFormation resolves is the one
691
+ # the cache entry was written for.
692
+ def vpc_arn
693
+ Fn.sub("arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:vpc/${VpcId}",
694
+ "VpcId" => vpc_id)
695
+ end
696
+
697
+ def vpc_cidr_block
698
+ @answer.fetch("cidr")
699
+ end
700
+
701
+ # nil: the answer names the subnets' routes, not the gateway, as the
702
+ # CDK's LookedUpVpc leaves the attribute unset.
703
+ def internet_gateway_id
704
+ nil
705
+ end
706
+
707
+ # nil both: the answer does not say. Reading them takes
708
+ # DescribeVpcAttribute, one call per flag, which the CDK's lookup
709
+ # provider does not make either.
710
+ def dns_support_enabled
711
+ nil
712
+ end
713
+
714
+ def dns_hostnames_enabled
715
+ nil
716
+ end
717
+
718
+ def vpc_default_network_acl
719
+ raise_lookup_has_no_resource("vpc_default_network_acl")
720
+ end
721
+
722
+ def vpc_default_security_group
723
+ raise_lookup_has_no_resource("vpc_default_security_group")
724
+ end
725
+
726
+ # No resource to name: where a Ref of the VPC was meant, vpc_id is
727
+ # what a consumer writes.
728
+ def logical_id
729
+ raise_lookup_has_no_resource("logical_id")
730
+ end
731
+
732
+ def public_subnet_ids
733
+ @public_subnets
734
+ end
735
+
736
+ def private_subnet_ids
737
+ @private_subnets
738
+ end
739
+
740
+ def isolated_subnet_ids
741
+ @isolated_subnets
742
+ end
743
+
744
+ private
745
+
746
+ # The answer this construct reads, as the lookup provider wrote it:
747
+ # "vpc_id", "cidr", "owner_account_id", "region",
748
+ # "availability_zones" and one "subnet_groups" entry per non-empty
749
+ # reachability type. An entry of another shape is refused, not
750
+ # partly read: a cache this tool did not write is a hand edit.
751
+ def self.validate_answer(answer, cache, query)
752
+ groups = answer["subnet_groups"]
753
+ zones = answer["availability_zones"]
754
+ subnets_ok = groups.is_a?(Array) && groups.all? do |group|
755
+ group.is_a?(Hash) && LOOKUP_TYPES.key?(group["type"]) && group["name"].is_a?(String) &&
756
+ group["subnets"].is_a?(Array) && group["subnets"].all? do |subnet|
757
+ subnet.is_a?(Hash) && subnet["subnet_id"].is_a?(String) && subnet["route_table_id"].is_a?(String) &&
758
+ subnet["cidr"].is_a?(String) && subnet["availability_zone"].is_a?(String)
759
+ end
760
+ end
761
+ return answer if answer["vpc_id"].is_a?(String) && !answer["vpc_id"].empty? &&
762
+ answer["cidr"].is_a?(String) && !answer["cidr"].empty? &&
763
+ zones.is_a?(Array) && zones.all?(String) && subnets_ok
764
+
765
+ raise PreconditionError, "The cache #{cache} answers #{query.key} with an entry this tool did not write: " \
766
+ "a VPC answer carries vpc_id, cidr, owner_account_id, region, availability_zones and subnet_groups, " \
767
+ "each subnet with its subnet_id, route_table_id, cidr and availability_zone. " \
768
+ "Remove the entry and run `ruby-cdk lookup` again."
769
+ end
770
+
771
+ def self.lookup_stack(scope, id)
772
+ stack = scope.is_a?(Construct) ? scope.stack : nil
773
+ return stack if stack
774
+
775
+ raise UsageError, "Vpc.from_lookup is made in a Stack: Vpc.from_lookup(stack, #{id.inspect}), " \
776
+ "got #{scope.inspect} as its scope"
777
+ end
778
+
779
+ # The query's arguments as flat pairs for the cache key
780
+ # (Core::Context): "vpc-id" and one "tag.<Name>" per tag. The tags
781
+ # travel as the tags of a Stack do (Stack#tag_hash): String or
782
+ # Symbol, turned into strings.
783
+ def self.lookup_args(id, scope, vpc_id, tags)
784
+ where = "#{scope.path}: the Vpc #{id.inspect}"
785
+ unless vpc_id.nil? || (vpc_id.is_a?(String) && !vpc_id.empty?)
786
+ raise UsageError, "#{where}: all arguments to from_lookup must be concrete: vpc_id takes a VPC id " \
787
+ "String, got #{vpc_id.inspect}"
788
+ end
789
+ unless tags.nil? || tags.is_a?(Hash)
790
+ raise UsageError, "#{where}: tags takes a Hash, got #{tags.inspect}"
791
+ end
792
+
793
+ args = {}
794
+ args["vpc-id"] = vpc_id if vpc_id
795
+ (tags || {}).each do |name, value|
796
+ name = name.is_a?(String) ? name : (name.is_a?(Symbol) ? name.name : nil)
797
+ value = value.is_a?(String) ? value : (value.is_a?(Symbol) ? value.name : nil)
798
+ unless name && !name.empty? && value
799
+ raise UsageError, "#{where}: each tag takes a String or Symbol name and value, got " \
800
+ "#{name.inspect} => #{value.inspect}"
801
+ end
802
+
803
+ args["tag.#{name}"] = value
804
+ end
805
+ args.freeze
806
+ end
807
+
808
+ def raise_lookup_has_no_resource(what)
809
+ raise UsageError, "#{path}: a looked-up VPC synthesizes no resources, so it answers no #{what}; " \
810
+ "the VPC, its subnets and their route tables already exist. Use #{path}.vpc_id where a Ref was meant."
811
+ end
812
+
813
+ # The subnet ids of one group, in the order the answer holds them
814
+ # (the lookup provider sorts by zone and id).
815
+ def subnets_of(type)
816
+ group = @answer["subnet_groups"].find { |entry| entry["type"] == type }
817
+ group ? group["subnets"].map { |subnet| subnet.fetch("subnet_id") } : []
818
+ end
819
+ end
820
+ end
821
+ end
822
+ end