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,159 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+
5
+ module RubyCdk
6
+ module EC2
7
+ # The IPv4 arithmetic behind the Vpc's automatic subdivision: the port of
8
+ # aws-ec2/lib/network-util.ts, read at commit
9
+ # c070afb54b9e4dbddd52a85a21077fe970354985, Apache-2.0. CidrBlock is the
10
+ # CDK's CidrBlock (network-util.ts:242-372), NetworkBuilder its
11
+ # NetworkBuilder (network-util.ts:157-235): a network is carved from the
12
+ # front, one block at a time, and the subnet sizes the Vpc does not name
13
+ # itself are the remaining space divided evenly.
14
+ #
15
+ # The refusals are the CDK's, in its words: an IP that is not four octets
16
+ # of 0 to 255 (network-util.ts:32-39, "is not valid"), a mask outside /16
17
+ # to /28 (network-util.ts:200-202, "is not a valid VPC CIDR range. VPCs
18
+ # must be between /16 and /28 and the minimum subnet size is /28."), and
19
+ # a carve that does not fit (network-util.ts:204-205, "exceeds remaining
20
+ # space"). Where JavaScript's parseInt would read "1e2" as 1, the octet
21
+ # check here is exact: the CDK's tolerance is the language's, not a rule.
22
+ class CidrBlock
23
+ # network-util.ts:12, InvalidCidrRangeError's message, over the mask.
24
+ INVALID_RANGE_SUFFIX = " is not a valid VPC CIDR range. VPCs must be between /16 and /28 and the minimum subnet size is /28."
25
+
26
+ attr_reader :mask, :cidr, :network_size
27
+
28
+ # The number of addresses in a mask (network-util.ts:261-263).
29
+ def self.netsize(mask)
30
+ 2**(32 - mask)
31
+ end
32
+
33
+ # "10.0.0.0/16" or (address as a number, mask). An address that is not
34
+ # the beginning of its block is rounded down to it
35
+ # (network-util.ts:296-306).
36
+ def initialize(cidr_or_address, mask = nil)
37
+ if mask.nil?
38
+ raise UsageError, "#{cidr_or_address}#{INVALID_RANGE_SUFFIX}" unless cidr_or_address.is_a?(String) && cidr_or_address.include?("/")
39
+
40
+ text, mask_text = cidr_or_address.split("/", 2)
41
+ @mask = parse_mask(mask_text)
42
+ @network_address = CidrBlock.ip_to_num(text) + CidrBlock.netsize(@mask) - 1
43
+ else
44
+ @mask = mask
45
+ @network_address = cidr_or_address + CidrBlock.netsize(mask) - 1
46
+ end
47
+ @network_size = CidrBlock.netsize(@mask)
48
+ @cidr = "#{min_ip}/#{@mask}"
49
+ end
50
+
51
+ # The number form of the first address (network-util.ts:342-345).
52
+ def min_address
53
+ remainder = @network_address % @network_size
54
+ @network_address - remainder
55
+ end
56
+
57
+ # The number form of the last address (network-util.ts:351-354).
58
+ def max_address
59
+ min_address + @network_size - 1
60
+ end
61
+
62
+ def min_ip
63
+ CidrBlock.num_to_ip(min_address)
64
+ end
65
+
66
+ def max_ip
67
+ CidrBlock.num_to_ip(max_address)
68
+ end
69
+
70
+ # The next block of the same size (network-util.ts:360-362).
71
+ def next_block
72
+ CidrBlock.new(max_address + 1, @mask)
73
+ end
74
+
75
+ # "174.66.173.168" as a number (network-util.ts:55-66). An invalid
76
+ # address is the CDK's refusal, in its words.
77
+ def self.ip_to_num(ip_address)
78
+ octets = ip_address.to_s.split(".")
79
+ unless octets.length == 4 && octets.all? { |octet| valid_octet?(octet) }
80
+ raise UsageError, "#{ip_address} is not valid"
81
+ end
82
+
83
+ octets.each_with_index.sum { |octet, i| Integer(octet, 10) * 256**(3 - i) }
84
+ end
85
+
86
+ # A number as "174.66.173.168" (network-util.ts:78-95).
87
+ def self.num_to_ip(ip_num)
88
+ address = (0..3).map { |i| (ip_num / 256**(3 - i)) % 256 }
89
+ ip = address.join(".")
90
+ raise UsageError, "#{ip} is not a valid IP Address" unless ip.split(".").all? { |octet| valid_octet?(octet) }
91
+
92
+ ip
93
+ end
94
+
95
+ # network-util.ts:32-39: a whole number from 0 to 255. Where
96
+ # JavaScript's parseInt reads "1e2" as 1, the check is exact.
97
+ def self.valid_octet?(octet)
98
+ /\A\d+\z/.match?(octet) && Integer(octet, 10) <= 255
99
+ end
100
+ private_class_method :valid_octet?
101
+
102
+ def parse_mask(mask_text)
103
+ unless /\A\d+\z/.match?(mask_text.to_s)
104
+ raise UsageError, "the netmask after the slash must be a number, got #{mask_text.inspect}"
105
+ end
106
+
107
+ Integer(mask_text, 10)
108
+ end
109
+ private :parse_mask
110
+ end
111
+
112
+ # Carves subnets out of a network, from the front (network-util.ts:157-235).
113
+ class NetworkBuilder
114
+ attr_reader :network_cidr
115
+
116
+ def initialize(cidr)
117
+ @network_cidr = CidrBlock.new(cidr)
118
+ @next_available_ip = @network_cidr.min_address
119
+ end
120
+
121
+ # One subnet of mask (network-util.ts:191-193).
122
+ def add_subnet(mask)
123
+ add_subnets(mask, 1).first
124
+ end
125
+
126
+ # count subnets of one mask, contiguous, in order
127
+ # (network-util.ts:199-215). The mask has to be a subnet size, and the
128
+ # carve has to fit: the refusals are the CDK's.
129
+ def add_subnets(mask, count)
130
+ unless mask.is_a?(Integer) && mask >= 16 && mask <= 28
131
+ raise UsageError, "x.x.x.x/#{mask}#{CidrBlock::INVALID_RANGE_SUFFIX}"
132
+ end
133
+
134
+ max_ip = @next_available_ip + (CidrBlock.netsize(mask) * count)
135
+ if @network_cidr.max_address < max_ip - 1
136
+ raise UsageError, "#{count} of /#{mask} exceeds remaining space of #{@network_cidr.cidr}"
137
+ end
138
+
139
+ subnets = Array.new(count) do
140
+ subnet = CidrBlock.new(@next_available_ip, mask)
141
+ @next_available_ip = subnet.next_block.min_address
142
+ subnet.cidr
143
+ end
144
+ subnets
145
+ end
146
+
147
+ # The largest mask that divides what is left into count even parts
148
+ # (network-util.ts:230-234). For count zero there is nothing to divide,
149
+ # and the caller allocates nothing.
150
+ def mask_for_remaining_subnets(subnet_count)
151
+ return nil if subnet_count.zero?
152
+
153
+ remaining = @network_cidr.max_address - @next_available_ip + 1
154
+ ips_per_subnet = (remaining.to_f / subnet_count).floor
155
+ 32 - Math.log2(ips_per_subnet).floor
156
+ end
157
+ end
158
+ end
159
+ end
@@ -9,7 +9,8 @@
9
9
  # RubyCdk::DynamoDB::Table, RubyCdk::SQS::Queue, RubyCdk::SNS::Topic,
10
10
  # RubyCdk::Logs::LogGroup, RubyCdk::SSM::Parameter,
11
11
  # RubyCdk::SecretsManager::Secret, RubyCdk::Events::Rule,
12
- # RubyCdk::ApiGateway::RestApi, RubyCdk::KMS::Key
12
+ # RubyCdk::ApiGateway::RestApi, RubyCdk::KMS::Key, RubyCdk::EC2::Vpc,
13
+ # RubyCdk::Route53::HostedZone and its record sets
13
14
  #
14
15
  # The sources behind the defaults were read in aws/aws-cdk at commit
15
16
  # c070afb54b9e4dbddd52a85a21077fe970354985 (main, read on 2026-11-25,
@@ -66,3 +67,6 @@ require_relative "constructs/secret"
66
67
  require_relative "constructs/schedule"
67
68
  require_relative "constructs/events_rule"
68
69
  require_relative "constructs/restapi"
70
+ require_relative "constructs/vpc"
71
+ require_relative "constructs/hosted_zone"
72
+ require_relative "constructs/record_set"
@@ -9,7 +9,7 @@ module RubyCdk
9
9
  # Where synthesis writes when neither the app file nor the command says.
10
10
  DEFAULT_OUT_DIR = "cdk.out"
11
11
 
12
- attr_reader :env, :out_dir, :stack_name_prefix, :stateful_default
12
+ attr_reader :env, :out_dir, :stack_name_prefix, :stateful_default, :context_file
13
13
 
14
14
  class << self
15
15
  # The App the command line runs: the one build! returned, or when there
@@ -43,7 +43,11 @@ module RubyCdk
43
43
  raise UsageError, "App.build!: out_dir must be the path of a directory or nil, got #{out_dir.inspect}"
44
44
  end
45
45
 
46
- created = with_out_dir_of_command(out_dir) { newly_created { evaluate_app_file(path) } }
46
+ created = with_out_dir_of_command(out_dir) do
47
+ with_context_file_of_command(File.expand_path(Context::FILE_NAME, File.dirname(path))) do
48
+ newly_created { evaluate_app_file(path) }
49
+ end
50
+ end
47
51
  case created.length
48
52
  when 1
49
53
  @current = created.first
@@ -67,6 +71,14 @@ module RubyCdk
67
71
  @out_dir_of_command
68
72
  end
69
73
 
74
+ # The context cache beside the app file while the app file runs, the
75
+ # same window as out_dir_of_command: build! names it, an App records it
76
+ # at construction, and the lookups of D-022 read it. nil the rest of
77
+ # the time, so an App created outside a command has no cache to read.
78
+ def context_file_of_command
79
+ @context_file_of_command
80
+ end
81
+
70
82
  # Every App created in this process, in creation order.
71
83
  def instances
72
84
  (@instances ||= []).dup.freeze
@@ -105,6 +117,17 @@ module RubyCdk
105
117
  ensure
106
118
  @out_dir_of_command = before
107
119
  end
120
+
121
+ # The same window for the context cache file beside the app file
122
+ # (decision D-022): the lookups the app file makes read it, and a
123
+ # lookup that misses names it.
124
+ def with_context_file_of_command(path)
125
+ before = @context_file_of_command
126
+ @context_file_of_command = path
127
+ yield
128
+ ensure
129
+ @context_file_of_command = before
130
+ end
108
131
  end
109
132
 
110
133
  def initialize(env: nil, out_dir: nil, stack_name_prefix: nil, stateful_default: :retain_except_on_create, &block)
@@ -122,6 +145,7 @@ module RubyCdk
122
145
  super(nil, "App")
123
146
  @env = env
124
147
  @out_dir = directory
148
+ @context_file = App.context_file_of_command
125
149
  @stack_name_prefix = stack_name_prefix
126
150
  @stateful_default = Core::Stateful.validate_default!(stateful_default)
127
151
  App.register(self)
@@ -139,8 +163,10 @@ module RubyCdk
139
163
  #
140
164
  # Declared here because it is the tree's contract. The synth component
141
165
  # implements it by reopening this class: core does not depend on synth.
166
+ # :nocov: contract stub replaced at load time when the umbrella loads synth
142
167
  def synth(validate: true)
143
168
  raise NotImplementedError, "added by the synth component"
144
169
  end
170
+ # :nocov:
145
171
  end
146
172
  end
@@ -98,8 +98,10 @@ module RubyCdk
98
98
  #
99
99
  # Declared here because it is the tree's contract. The cfn component
100
100
  # implements it by reopening this class: core does not depend on cfn.
101
+ # :nocov: contract stub replaced at load time when the umbrella loads cfn
101
102
  def resource(id, type, properties: nil, depends_on: [], condition: nil, deletion_policy: nil, update_replace_policy: nil, metadata: {}, **opts)
102
103
  raise NotImplementedError, "added by the cfn component"
103
104
  end
105
+ # :nocov:
104
106
  end
105
107
  end
@@ -0,0 +1,138 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "../errors"
5
+
6
+ module RubyCdk
7
+ # The context cache beside the app file (decision D-022). A lookup of an
8
+ # existing resource is a command, never a side effect of synth:
9
+ # `ruby-cdk lookup` calls AWS and writes its answers into
10
+ # `cdk.context.json` in the app file's directory, and synthesis reads that
11
+ # file and nothing else. The file is committed, so two machines read the
12
+ # same answers and synthesize the same template.
13
+ #
14
+ # The file is one JSON object whose keys are queries and whose values are
15
+ # answers. A key names the provider, the environment the answer is valid
16
+ # for, and the query's arguments, so a second synthesis with the same props
17
+ # hits it and an entry cannot be read for the wrong account or region (a
18
+ # wrong-environment hit is worse than a miss). The values carry no
19
+ # timestamp and nothing machine-derived: nothing in the file varies between
20
+ # machines, and nothing in it enters a template verbatim but what AWS
21
+ # answered.
22
+ #
23
+ # This module owns the file and the keys. The answers' shapes belong to the
24
+ # provider that wrote them and the construct that reads them; today there
25
+ # is one, the VPC (EC2::Vpc.from_lookup reads it, Deploy::Sdk::Ec2Client
26
+ # writes it).
27
+ module Context
28
+ # The CDK's file name, beside the app file (App.build! computes the path).
29
+ FILE_NAME = "cdk.context.json"
30
+
31
+ # One lookup query: the provider, the environment the answer must be
32
+ # valid for, and the arguments as flat String pairs (for the VPC:
33
+ # "vpc-id" => ..., one "tag.<Name>" => <value> per tag). The arguments
34
+ # are concrete by construction: the construct that builds a Query has
35
+ # already refused tokens.
36
+ Query = Data.define(:provider, :account, :region, :args) do
37
+ # The key the answer is cached under.
38
+ def key
39
+ Context.key(self)
40
+ end
41
+
42
+ # The query as a person reads it in a refusal: "tag.Name=main, vpc-id=vpc-0abc".
43
+ def describe
44
+ args.keys.sort.map { |name| "#{name}=#{args[name]}" }.join(", ")
45
+ end
46
+ end
47
+
48
+ # Exit 1. The cache has no answer for a query the app makes: synthesis
49
+ # stops with the command that answers it. The lookup command catches the
50
+ # class, answers the query, writes the cache and synthesizes again.
51
+ class Miss < PreconditionError
52
+ attr_reader :query, :path, :where
53
+
54
+ # The key the missed answer is cached under, as the lookup command
55
+ # names it.
56
+ def key
57
+ query.key
58
+ end
59
+
60
+ # where names the construct that asked, as "the Vpc \"Net\" of the
61
+ # stack \"blog\""; nil when the caller has no better words.
62
+ def initialize(query:, path:, where: nil)
63
+ @query = query
64
+ @path = path
65
+ @where = where || "a construct of this app"
66
+ detail = query.describe.empty? ? "without further arguments" : "(#{query.describe})"
67
+ super("This app reads context that is not cached yet: #{where} makes a #{query.provider} lookup " \
68
+ "#{detail} for account #{query.account} in #{query.region}, and #{path} holds no answer for it. " \
69
+ "Nothing was synthesized.\n" \
70
+ "Run `ruby-cdk lookup`, then run the command again. The lookup calls AWS and writes the answer into " \
71
+ "#{path}, which is committed, so two machines synthesize the same template.")
72
+ end
73
+ end
74
+
75
+ class << self
76
+ # The key one answer is cached under: "provider:account=...:region=...:arg=...",
77
+ # the arguments sorted, a colon in a name or value quoted as the CDK
78
+ # quotes its own keys (context-provider.ts, colonQuote). The same query
79
+ # always gives the same key, so a repeated synthesis hits.
80
+ def key(query)
81
+ props = [ "account=#{query.account}", "region=#{query.region}" ]
82
+ query.args.each { |name, value| props << "#{quote(name)}=#{quote(value)}" }
83
+ "#{query.provider}:#{props.sort.join(":")}"
84
+ end
85
+
86
+ # The answer cached for a query, or Miss. An entry whose payload names
87
+ # another environment than its key does is refused, not read: the key
88
+ # and the entry disagreeing means the file was edited by hand.
89
+ def answer(path, query, where: nil)
90
+ entry = read(path)[query.key]
91
+ raise Miss.new(query: query, path: path, where: where) unless entry
92
+
93
+ unless entry["region"] == query.region && entry["owner_account_id"] == query.account
94
+ raise PreconditionError, "The cache #{path} answers #{query.key} with an entry for account " \
95
+ "#{entry["owner_account_id"].inspect} in region #{entry["region"].inspect}, but this app asks for " \
96
+ "account #{query.account} in region #{query.region}. The key and the entry disagree, so the file was " \
97
+ "edited by hand: correct it or remove the entry, then run `ruby-cdk lookup` again."
98
+ end
99
+
100
+ entry
101
+ end
102
+
103
+ # Every entry of a cache file, {} when there is none yet. A file that
104
+ # is not an object of objects is refused, not silently ignored.
105
+ def read(path)
106
+ return {} unless File.file?(path)
107
+
108
+ entries = JSON.parse(File.read(path))
109
+ unless entries.is_a?(Hash) && entries.keys.all?(String) && entries.values.all?(Hash)
110
+ raise PreconditionError, "#{path} is not a context cache this tool wrote: the top level must be a " \
111
+ "JSON object whose values are objects. Correct it by hand or remove it, then run `ruby-cdk lookup` again."
112
+ end
113
+
114
+ entries
115
+ rescue JSON::ParserError => e
116
+ raise PreconditionError, "#{path} is not valid JSON (#{e.message}), so it cannot be read as a context " \
117
+ "cache. Correct it by hand or remove it, then run `ruby-cdk lookup` again."
118
+ end
119
+
120
+ # Writes the entries in place. The keys are sorted, so the bytes do not
121
+ # depend on the order the queries were answered in, and two machines
122
+ # with the same answers hold the same file. Values are written as the
123
+ # provider shaped them: strings, arrays and objects, no timestamps.
124
+ def write(path, entries)
125
+ File.write(path, "#{JSON.pretty_generate(entries.sort.to_h)}\n")
126
+ path
127
+ end
128
+
129
+ private
130
+
131
+ # context-provider.ts, colonQuote: `$` doubles, `:` becomes `$:`, so
132
+ # that the key splits back on its own colons.
133
+ def quote(text)
134
+ text.to_s.gsub("$", "$$").gsub(":", "$:")
135
+ end
136
+ end
137
+ end
138
+ end
@@ -127,9 +127,11 @@ module RubyCdk
127
127
  #
128
128
  # Declared here because it is the tree's contract. The assets component
129
129
  # implements it by reopening this class: core does not depend on assets.
130
+ # :nocov: contract stub replaced at load time when the umbrella loads assets
130
131
  def asset
131
132
  raise NotImplementedError, "added by the assets component"
132
133
  end
134
+ # :nocov:
133
135
 
134
136
  # "#{stack_name}-#{suffix}-<hash>": lower-case letters, digits and hyphens.
135
137
  # The hash is the first eight hex characters of SHA-256 over
@@ -183,9 +185,11 @@ module RubyCdk
183
185
  #
184
186
  # Declared here because it is the tree's contract. The synth component
185
187
  # implements it by reopening this class: core does not depend on synth.
188
+ # :nocov: contract stub replaced at load time when the umbrella loads synth
186
189
  def to_template
187
190
  raise NotImplementedError, "added by the synth component"
188
191
  end
192
+ # :nocov:
189
193
 
190
194
  # The stacks this one depends on, in the order they were added.
191
195
  def dependencies
data/lib/ruby_cdk/core.rb CHANGED
@@ -3,6 +3,7 @@
3
3
  require_relative "values"
4
4
  require_relative "core/ids"
5
5
  require_relative "core/stateful"
6
+ require_relative "core/context"
6
7
  require_relative "core/elements"
7
8
  require_relative "core/construct"
8
9
  require_relative "core/stack"