ruby-cdk 0.1.0 → 0.2.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 (37) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +136 -1
  3. data/README.md +39 -20
  4. data/THIRD_PARTY_NOTICES.md +56 -2
  5. data/data/spec/META.json +10 -10
  6. data/data/spec/model.json.gz +0 -0
  7. data/lib/ruby_cdk/cli/diff.rb +88 -7
  8. data/lib/ruby_cdk/cli/new.rb +13 -16
  9. data/lib/ruby_cdk/cli/operation.rb +28 -4
  10. data/lib/ruby_cdk/cli/session.rb +20 -3
  11. data/lib/ruby_cdk/cli.rb +14 -1
  12. data/lib/ruby_cdk/constructs/bucket.rb +84 -16
  13. data/lib/ruby_cdk/constructs/events_rule.rb +245 -0
  14. data/lib/ruby_cdk/constructs/function.rb +65 -6
  15. data/lib/ruby_cdk/constructs/kms_alias.rb +90 -0
  16. data/lib/ruby_cdk/constructs/kms_key.rb +436 -0
  17. data/lib/ruby_cdk/constructs/queue.rb +94 -15
  18. data/lib/ruby_cdk/constructs/restapi.rb +234 -0
  19. data/lib/ruby_cdk/constructs/schedule.rb +92 -0
  20. data/lib/ruby_cdk/constructs/secret.rb +104 -0
  21. data/lib/ruby_cdk/constructs/ssm_parameter.rb +238 -0
  22. data/lib/ruby_cdk/constructs/table.rb +87 -10
  23. data/lib/ruby_cdk/constructs/topic.rb +25 -14
  24. data/lib/ruby_cdk/constructs.rb +16 -4
  25. data/lib/ruby_cdk/deploy/deployer.rb +232 -16
  26. data/lib/ruby_cdk/deploy/fakes.rb +31 -3
  27. data/lib/ruby_cdk/deploy/hotswap.rb +175 -0
  28. data/lib/ruby_cdk/deploy/parameters.rb +16 -8
  29. data/lib/ruby_cdk/deploy/ports.rb +18 -0
  30. data/lib/ruby_cdk/deploy/sdk_adapters.rb +23 -0
  31. data/lib/ruby_cdk/deploy.rb +1 -0
  32. data/lib/ruby_cdk/diff/destructive.rb +68 -0
  33. data/lib/ruby_cdk/diff/template.rb +13 -2
  34. data/lib/ruby_cdk/diff.rb +1 -0
  35. data/lib/ruby_cdk/errors.rb +13 -0
  36. data/lib/ruby_cdk/version.rb +1 -1
  37. metadata +10 -1
@@ -0,0 +1,238 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+ require_relative "../fn"
5
+ require_relative "../lazy"
6
+ require_relative "grant"
7
+
8
+ module RubyCdk
9
+ module SSM
10
+ # An SSM parameter: the port of the CDK's StringParameter and
11
+ # StringListParameter (aws-ssm/lib/parameter.ts), read at commit
12
+ # c070afb54b9e4dbddd52a85a21077fe970354985, Apache-2.0.
13
+ #
14
+ # RubyCdk::SSM::Parameter.new(stack, "Token",
15
+ # name: "/app/token", value: secret, type: :string)
16
+ # RubyCdk::SSM::Parameter.new(stack, "Hosts",
17
+ # value: ["a.internal", "b.internal"], type: :string_list)
18
+ #
19
+ # The CDK splits the two kinds over two classes; here one class takes
20
+ # type: :string or :string_list, the two values the model lists for the
21
+ # Type property, and writes Type accordingly. The CDK's StringParameter
22
+ # writes ParameterType.STRING (parameter.ts:759), the StringListParameter
23
+ # ParameterType.STRING_LIST (parameter.ts:889); a string list is joined
24
+ # with a comma, as the CDK's Fn.join(',', props.stringListValue) is
25
+ # (parameter.ts:890), and a literal list resolves to the joined string.
26
+ #
27
+ # The value may be an intrinsic - Fn.sub of a deploy-time value - and the
28
+ # allowed_pattern is then not checked, as the CDK leaves unresolved tokens
29
+ # alone (_assertValidValue, parameter.ts:915-925). The name checks are the
30
+ # CDK's: at most 2048 characters and only letters, digits and .-_/
31
+ # (validateParameterName, parameter.ts:929-937), and a name with a slash
32
+ # must begin with one, as the ARN builder requires (util.ts:21-23).
33
+ #
34
+ # SecureString is refused: the CDK itself says a SecureString parameter
35
+ # cannot be created directly (parameter.ts:311-315), the model lists only
36
+ # String and StringList for Type, and a SecureString value is encrypted
37
+ # with a KMS key - reading it needs kms:Decrypt on that key, which this
38
+ # wave's grants cannot carry without a Key construct. Reference one with
39
+ # Fn.sub("{{resolve:ssm-secure:...}}") on the reader's side instead, or
40
+ # wait for the KMS Key construct.
41
+ #
42
+ # The ARN has no GetAtt on this type: it is built from the name, as the
43
+ # CDK's arnForParameterName builds it (util.ts:17-46) - simple name and
44
+ # path name read the same here, "parameter" then the name without its
45
+ # leading slash. Built with Fn.sub over CloudFormation's own pseudo
46
+ # parameters, so it works in a stack with no concrete env.
47
+ #
48
+ # The grants are the CDK's (parameter.ts:203-231, at the pinned commit):
49
+ # read is ssm:DescribeParameters, ssm:GetParameters, ssm:GetParameter and
50
+ # ssm:GetParameterHistory, in that order; write is ssm:PutParameter. All
51
+ # on the ARN, to the principal's own policy. The CDK adds
52
+ # encryptionKey.grantDecrypt/grantEncrypt beside them when the parameter
53
+ # carries a KMS key prop; there is no key prop here, so no KMS actions
54
+ # travel with the grant, as in the CDK without one.
55
+ class Parameter < Construct
56
+ # The CDK's two createable types (parameter.ts:759, 889).
57
+ TYPES = { string: "String", string_list: "StringList" }.freeze
58
+
59
+ # The CDK's tiers (parameter.ts:343-356).
60
+ TIERS = { standard: "Standard", advanced: "Advanced", intelligent_tiering: "Intelligent-Tiering" }.freeze
61
+
62
+ # The CDK's data types (parameter.ts:329-338).
63
+ DATA_TYPES = [ "text", "aws:ec2:image" ].freeze
64
+
65
+ # The CDK's read actions, in its order (parameter.ts:209-214).
66
+ READ_ACTIONS = [
67
+ "ssm:DescribeParameters", "ssm:GetParameters", "ssm:GetParameter", "ssm:GetParameterHistory"
68
+ ].freeze
69
+
70
+ # The CDK's write action (parameter.ts:228).
71
+ WRITE_ACTIONS = [ "ssm:PutParameter" ].freeze
72
+
73
+ attr_reader :type
74
+
75
+ def initialize(scope, id, value:, type: :string, name: nil, description: nil, allowed_pattern: nil,
76
+ tier: nil, data_type: nil)
77
+ super(scope, id)
78
+ @type = valid_type(type)
79
+ @name = valid_name(name)
80
+ @description = valid_description(description)
81
+ @tier = valid_tier(tier)
82
+ @data_type = valid_data_type(data_type)
83
+ @values = valid_values(value, allowed_pattern)
84
+
85
+ @resource = resource("Resource", "AWS::SSM::Parameter",
86
+ Name: @name,
87
+ Type: TYPES[@type],
88
+ Value: rendered_value,
89
+ Description: @description,
90
+ AllowedPattern: allowed_pattern,
91
+ Tier: @tier,
92
+ DataType: @data_type)
93
+ end
94
+
95
+ # The logical ID of the AWS::SSM::Parameter under this construct, so that
96
+ # the parameter can sit in another resource's depends_on:.
97
+ def logical_id
98
+ @resource.logical_id
99
+ end
100
+
101
+ # The parameter's name: the one given, or the Ref of the resource, as the
102
+ # CDK's parameterName is the resource's ref (parameter.ts:766).
103
+ def parameter_name
104
+ @name || Fn.ref(@resource)
105
+ end
106
+
107
+ # The parameter's ARN, built from the name (parameter.ts:767-770 and
108
+ # util.ts, arnForParameterName).
109
+ def arn
110
+ Fn.sub("arn:${AWS::Partition}:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${ParameterName}",
111
+ "ParameterName" => @name ? @name.delete_prefix("/") : Fn.ref(@resource))
112
+ end
113
+
114
+ # Grants the read actions to the principal (parameter.ts:203-217). The
115
+ # CDK adds a KMS grantDecrypt beside them when the parameter carries an
116
+ # encryption key; there is no key prop here, so the four SSM actions
117
+ # alone travel with the grant.
118
+ def grant_read(principal)
119
+ Constructs::Grant.add_to_principal(principal, READ_ACTIONS, [ arn ])
120
+ end
121
+
122
+ # Grants the write action (parameter.ts:222-231).
123
+ def grant_write(principal)
124
+ Constructs::Grant.add_to_principal(principal, WRITE_ACTIONS, [ arn ])
125
+ end
126
+
127
+ private
128
+
129
+ # :secure_string is refused with the KMS implication spelled out; see the
130
+ # header.
131
+ def valid_type(value)
132
+ return value if TYPES.key?(value)
133
+
134
+ raise UsageError, "#{path}: type takes :string or :string_list (SecureString is not createable: the CDK " \
135
+ "says so itself, parameter.ts:311-315, and reading one needs kms:Decrypt on its KMS key), got #{value.inspect}"
136
+ end
137
+
138
+ def valid_name(name)
139
+ return nil if name.nil?
140
+ raise UsageError, "#{path}: the name must be a String, got #{name.inspect}" unless name.is_a?(String)
141
+ raise UsageError, "#{path}: name cannot be longer than 2048 characters." if name.length > 2048
142
+ unless name.match?(%r{\A[/\w.-]+\z})
143
+ raise UsageError, "#{path}: name must only contain letters, numbers, and the following 4 symbols .-_\/; got #{name}"
144
+ end
145
+ if name.include?("/") && !name.start_with?("/")
146
+ raise UsageError, "#{path}: Parameter names must be fully qualified " \
147
+ "(if they include \"/\" they must also begin with a \"/\"): #{name}"
148
+ end
149
+
150
+ name
151
+ end
152
+
153
+ def valid_description(description)
154
+ return nil if description.nil?
155
+ unless description.is_a?(String)
156
+ raise UsageError, "#{path}: the description must be a String, got #{description.inspect}"
157
+ end
158
+ raise UsageError, "#{path}: Description cannot be longer than 1024 characters." if description.length > 1024
159
+
160
+ description
161
+ end
162
+
163
+ def valid_tier(tier)
164
+ return nil if tier.nil?
165
+ return TIERS[tier] if TIERS.key?(tier)
166
+
167
+ raise UsageError, "#{path}: tier takes #{TIERS.keys.map(&:inspect).join(", ")}, got #{tier.inspect}"
168
+ end
169
+
170
+ def valid_data_type(data_type)
171
+ return nil if data_type.nil?
172
+ return data_type if DATA_TYPES.include?(data_type)
173
+
174
+ raise UsageError, "#{path}: data_type takes #{DATA_TYPES.map(&:inspect).join(" or ")}, got #{data_type.inspect}"
175
+ end
176
+
177
+ # The value: a String or an intrinsic for :string, a list of them for
178
+ # :string_list. Literal values are checked against the allowed_pattern,
179
+ # as the CDK checks them (parameter.ts:740-742, 874-876); intrinsics are
180
+ # left alone, as its _assertValidValue leaves unresolved tokens.
181
+ def valid_values(value, allowed_pattern)
182
+ list = value.is_a?(Array) ? value : [ value ]
183
+ if @type == :string && value.is_a?(Array)
184
+ raise UsageError, "#{path}: a :string parameter takes one value, got an Array of #{value.length}"
185
+ end
186
+ list.each { |item| assert_value_kind(item) }
187
+ list.each { |item| assert_valid_value(item, allowed_pattern) }
188
+ list.each { |item| assert_no_comma(item) } if @type == :string_list
189
+ list
190
+ end
191
+
192
+ # A value is a String, an intrinsic or a Lazy; anything else is refused
193
+ # here rather than left for the value model, the way a physical name is.
194
+ def assert_value_kind(item)
195
+ return if item.is_a?(String) || item.is_a?(Hash) || item.is_a?(Lazy)
196
+
197
+ raise UsageError, "#{path}: the value must be a String, an intrinsic or a Lazy, got #{item.inspect}"
198
+ end
199
+
200
+ # The CDK's _assertValidValue (parameter.ts:915-925): a literal is tested
201
+ # with the pattern, unanchored, as RegExp#test is. A Hash (an intrinsic)
202
+ # or a Lazy is left alone.
203
+ def assert_valid_value(item, pattern)
204
+ return if item.is_a?(Hash) || item.is_a?(Lazy)
205
+ return if pattern.nil?
206
+ unless pattern.is_a?(String)
207
+ raise UsageError, "#{path}: allowed_pattern must be a String, got #{pattern.inspect}"
208
+ end
209
+
210
+ begin
211
+ regexp = Regexp.new(pattern)
212
+ rescue RegexpError => e
213
+ raise UsageError, "#{path}: allowed_pattern is not a regular expression: #{e.message}"
214
+ end
215
+ return if item.is_a?(String) && regexp.match?(item)
216
+
217
+ raise UsageError, "#{path}: The supplied value (#{item}) does not match the specified allowedPattern (#{pattern})"
218
+ end
219
+
220
+ # The CDK's StringListParameter check (parameter.ts:870-872).
221
+ def assert_no_comma(item)
222
+ return unless item.is_a?(String) && item.include?(",")
223
+
224
+ raise UsageError, "#{path}: Values of a StringList SSM Parameter cannot contain the ',' character. " \
225
+ "Use a string parameter instead."
226
+ end
227
+
228
+ # The comma-joined value of a string list, as the CDK writes it
229
+ # (parameter.ts:890); a literal list resolves to the joined string, as
230
+ # the CDK's resolved template shows it.
231
+ def rendered_value
232
+ return Fn.join(",", @values) if @type == :string_list
233
+
234
+ @values.first
235
+ end
236
+ end
237
+ end
238
+ end
@@ -3,6 +3,7 @@
3
3
  require_relative "../errors"
4
4
  require_relative "../fn"
5
5
  require_relative "grant"
6
+ require_relative "kms_key"
6
7
 
7
8
  module RubyCdk
8
9
  module DynamoDB
@@ -12,6 +13,7 @@ module RubyCdk
12
13
  # RubyCdk::DynamoDB::Table.new(stack, "Table",
13
14
  # partition_key: { name: "id", type: :string },
14
15
  # sort_key: { name: "sk", type: :number })
16
+ # RubyCdk::DynamoDB::Table.new(stack, "Table", partition_key: ..., encryption: :customer_managed)
15
17
  #
16
18
  # Defaults, and where they differ from the CDK (architecture section 7
17
19
  # wins; the rows are in section 21):
@@ -32,13 +34,30 @@ module RubyCdk
32
34
  # Key attributes take their type as a Symbol (:string, :number, :binary)
33
35
  # or as DynamoDB's own letter ("S", "N", "B").
34
36
  #
37
+ # Encryption is the CDK's parseEncryption (table.ts:1993-2046), its
38
+ # TableEncryption as Symbols. Nothing given: no SSESpecification, and
39
+ # DynamoDB's own key encrypts the table. :default writes SSEEnabled false;
40
+ # :aws_managed SSEEnabled true, the AWS-managed key; :customer_managed
41
+ # SSEEnabled true with SSEType KMS and the ARN of a customer-managed key in
42
+ # KMSMasterKeyId - the one given as encryption_key (a RubyCdk::KMS::Key, a
43
+ # key ARN or an intrinsic), or else a key created under the table, id Key,
44
+ # described "Customer-managed key auto-created for encrypting DynamoDB
45
+ # table at <the table's path>" and with rotation on. A key given with no
46
+ # encryption: implies :customer_managed; with another mode it is refused,
47
+ # as the CDK refuses it (table.ts:2012-2014). The deprecated
48
+ # serverSideEncryption is not carried: :aws_managed is its replacement.
49
+ #
35
50
  # The grants are the CDK's (aws-dynamodb/lib/table-grants.ts and perms.ts,
36
51
  # at the same commit): grant_read_data is the read actions and
37
52
  # DescribeTable, grant_read_write_data adds the write ones, each one
38
53
  # statement on the table's ARN - the CDK grants the same set as two
39
54
  # statements that its policy document minimizes into one, and this tool
40
55
  # writes the one. grant_full_access is dynamodb:*, and grant takes any
41
- # actions given.
56
+ # actions given. Under a customer-managed key, the three named grants also
57
+ # grant the key's actions on the key's ARN (KEY_READ_ACTIONS, and
58
+ # KEY_WRITE_ACTIONS beside them for the two that write; table-grants.ts:148-211),
59
+ # in the CDK's order: before the table's statement in grant_read_data, after
60
+ # it in the other two.
42
61
  class Table < Construct
43
62
  # The CDK's data read actions, then DescribeTable, in the order its
44
63
  # minimized statement carries (table-grants.ts, readData; its test).
@@ -57,16 +76,29 @@ module RubyCdk
57
76
  "dynamodb:DescribeTable"
58
77
  ].freeze
59
78
 
79
+ # The CDK's key actions (aws-dynamodb/lib/perms.ts, KEY_READ_ACTIONS and
80
+ # KEY_WRITE_ACTIONS).
81
+ KEY_READ_ACTIONS = [ "kms:Decrypt", "kms:DescribeKey" ].freeze
82
+ KEY_WRITE_ACTIONS = [ "kms:Encrypt", "kms:ReEncrypt*", "kms:GenerateDataKey*" ].freeze
83
+
84
+ # The two lists behind the read and write grants (table-grants.ts:172, 189, 209).
85
+ KEY_READ_WRITE_ACTIONS = (KEY_READ_ACTIONS + KEY_WRITE_ACTIONS).freeze
86
+
87
+ # The CDK's TableEncryption names (aws-dynamodb/lib/shared.ts:276-298),
88
+ # as this tool's Symbols: :default is the CDK's DEFAULT, AWS_OWNED.
89
+ ENCRYPTIONS = { default: "AWS_OWNED", aws_managed: "AWS_MANAGED", customer_managed: "CUSTOMER_MANAGED" }.freeze
90
+ private_constant :ENCRYPTIONS
91
+
60
92
  # The CDK's AttributeType names.
61
93
  ATTRIBUTE_TYPES = { string: "S", number: "N", binary: "B" }.freeze
62
94
 
63
95
  # The CDK's default provisioned capacities (table.ts:1372).
64
96
  DEFAULT_CAPACITY = 5
65
97
 
66
- attr_reader :partition_key, :sort_key, :billing
98
+ attr_reader :partition_key, :sort_key, :billing, :encryption, :encryption_key
67
99
 
68
100
  def initialize(scope, id, partition_key:, sort_key: nil, table_name: nil, billing: :on_demand,
69
- read_capacity: nil, write_capacity: nil, point_in_time_recovery: true)
101
+ read_capacity: nil, write_capacity: nil, point_in_time_recovery: true, encryption: nil, encryption_key: nil)
70
102
  super(scope, id)
71
103
  @partition_key = attribute(partition_key, "partition_key")
72
104
  @sort_key = sort_key && attribute(sort_key, "sort_key")
@@ -76,6 +108,8 @@ module RubyCdk
76
108
  raise(UsageError, "#{path}: billing takes :on_demand or :provisioned, got #{billing.inspect}")
77
109
  @pitr = point_in_time_recovery == true || point_in_time_recovery == false ? point_in_time_recovery :
78
110
  raise(UsageError, "#{path}: point_in_time_recovery takes true or false, got #{point_in_time_recovery.inspect}")
111
+ key = encryption_key && KMS.key_reference(encryption_key, "#{path}: encryption_key")
112
+ @encryption, @encryption_key, sse_specification = encryption_settings(encryption, key)
79
113
 
80
114
  # Grown with pushes rather than a literal of one, so that the key types
81
115
  # stay plain Strings for the checker.
@@ -98,7 +132,8 @@ module RubyCdk
98
132
  "ReadCapacityUnits" => read_capacity || DEFAULT_CAPACITY,
99
133
  "WriteCapacityUnits" => write_capacity || DEFAULT_CAPACITY
100
134
  } : nil,
101
- PointInTimeRecoverySpecification: { "PointInTimeRecoveryEnabled" => @pitr })
135
+ PointInTimeRecoverySpecification: { "PointInTimeRecoveryEnabled" => @pitr },
136
+ SSESpecification: sse_specification)
102
137
  end
103
138
 
104
139
  # The logical ID of the AWS::DynamoDB::Table under this construct, so
@@ -118,30 +153,72 @@ module RubyCdk
118
153
  end
119
154
 
120
155
  # Permits all data read operations from this table: the CDK's
121
- # grantReadData (table-grants.ts, readData, its minimized statement).
156
+ # grantReadData (table-grants.ts, readData, its minimized statement). The
157
+ # key's read actions come first under a customer-managed key, as in the
158
+ # CDK (table-grants.ts:150).
122
159
  def grant_read_data(principal)
160
+ KMS.grant_on_key(@encryption_key, principal, KEY_READ_ACTIONS) if @encryption_key
123
161
  Constructs::Grant.add_to_principal(principal, READ_DATA_ACTIONS, [ arn ])
124
162
  end
125
163
 
126
164
  # Permits all data read and write operations: the CDK's
127
- # grantReadWriteData (table-grants.ts, readWriteData).
165
+ # grantReadWriteData (table-grants.ts, readWriteData), then the key's
166
+ # read and write actions under a customer-managed key (table-grants.ts:189).
128
167
  def grant_read_write_data(principal)
129
- Constructs::Grant.add_to_principal(principal, READ_WRITE_DATA_ACTIONS, [ arn ])
168
+ grant = Constructs::Grant.add_to_principal(principal, READ_WRITE_DATA_ACTIONS, [ arn ])
169
+ KMS.grant_on_key(@encryption_key, principal, KEY_READ_WRITE_ACTIONS) if @encryption_key
170
+ grant
130
171
  end
131
172
 
132
- # Permits every operation on the table: the CDK's grantFullAccess.
173
+ # Permits every operation on the table: the CDK's grantFullAccess, then
174
+ # the key's read and write actions under a customer-managed key
175
+ # (table-grants.ts:209).
133
176
  def grant_full_access(principal)
134
- Constructs::Grant.add_to_principal(principal, [ "dynamodb:*" ], [ arn ])
177
+ grant = Constructs::Grant.add_to_principal(principal, [ "dynamodb:*" ], [ arn ])
178
+ KMS.grant_on_key(@encryption_key, principal, KEY_READ_WRITE_ACTIONS) if @encryption_key
179
+ grant
135
180
  end
136
181
 
137
182
  # Grants the actions given, as the CDK's grant does (table-grants.ts,
138
- # actions).
183
+ # actions): nothing is granted on the key.
139
184
  def grant(principal, *actions)
140
185
  Constructs::Grant.add_to_principal(principal, actions, [ arn ])
141
186
  end
142
187
 
143
188
  private
144
189
 
190
+ # The port of parseEncryption (table.ts:1993-2046), without the
191
+ # deprecated serverSideEncryption. Answers [the mode, the key, the
192
+ # SSESpecification or nil].
193
+ def encryption_settings(encryption, key)
194
+ encryption = valid_encryption(encryption) || (key ? :customer_managed : nil)
195
+ if key && encryption != :customer_managed
196
+ raise UsageError, "#{path}: encryption_key cannot be specified unless encryption is set to " \
197
+ "TableEncryption.CUSTOMER_MANAGED (it was set to #{ENCRYPTIONS.fetch(encryption)})"
198
+ end
199
+
200
+ case encryption
201
+ when nil
202
+ [ nil, nil, nil ]
203
+ when :customer_managed
204
+ key ||= KMS::Key.new(self, "Key",
205
+ description: "Customer-managed key auto-created for encrypting DynamoDB table at #{path}",
206
+ enable_key_rotation: true)
207
+ [ encryption, key, { "SSEEnabled" => true, "KMSMasterKeyId" => KMS.key_arn(key), "SSEType" => "KMS" } ]
208
+ when :aws_managed
209
+ [ encryption, nil, { "SSEEnabled" => true } ]
210
+ when :default
211
+ [ encryption, nil, { "SSEEnabled" => false } ]
212
+ end
213
+ end
214
+
215
+ def valid_encryption(value)
216
+ return nil if value.nil?
217
+ return value if ENCRYPTIONS.key?(value)
218
+
219
+ raise UsageError, "#{path}: encryption takes :default, :aws_managed, :customer_managed or nil, got #{value.inspect}"
220
+ end
221
+
145
222
  # { name:, type: } with the type as a Symbol or DynamoDB's letter.
146
223
  def attribute(key, what)
147
224
  unless key.is_a?(Hash) && key[:name].is_a?(String) && !key[:name].empty?
@@ -3,6 +3,7 @@
3
3
  require_relative "../errors"
4
4
  require_relative "../fn"
5
5
  require_relative "grant"
6
+ require_relative "kms_key"
6
7
 
7
8
  module RubyCdk
8
9
  module SNS
@@ -11,23 +12,26 @@ module RubyCdk
11
12
  #
12
13
  # RubyCdk::SNS::Topic.new(stack, "Events",
13
14
  # topic_name: "events", display_name: "Domain events")
15
+ # RubyCdk::SNS::Topic.new(stack, "Events", master_key: key)
14
16
  #
15
17
  # fifo: true marks the topic FIFO and names it with the .fifo suffix, as
16
18
  # the CDK's naming rule does; content_based_deduplication needs a FIFO
17
19
  # topic, and is refused on a standard one, as in the CDK. A topic is not a
18
20
  # retained type (architecture section 7).
19
21
  #
20
- # The grants are the CDK's (aws-sns/lib/topic-base.ts and its tests, at the
21
- # pinned commit): publish is sns:Publish on the topic's ARN; subscribe is
22
- # sns:Subscribe, the API call alone, as the CDK grants it.
22
+ # Encryption: master_key is the CDK's masterKey (topic.ts:47, 383) - a
23
+ # RubyCdk::KMS::Key, the ARN of a key that exists, or an intrinsic - and
24
+ # KmsMasterKeyId is written with its ARN, and only then. The resource has
25
+ # no managed-SSE property: AWS encrypts a new topic at rest with an
26
+ # SNS-managed key by default, so a topic without a key says nothing.
23
27
  #
24
- # Encryption: this tool takes no option and writes no property, as the CDK
25
- # at the pinned commit does (topic.ts writes KmsMasterKeyId only when a key
26
- # prop is given; there is no managed-SSE property on the resource): AWS
27
- # encrypts a new topic at rest with an SNS-managed key by default, so the
28
- # template says nothing. A customer-managed key needs KmsMasterKeyId,
29
- # which this tool does not yet take; architecture section 21 records the
30
- # row.
28
+ # The grants are the CDK's (aws-sns/grants.json and topic-base.ts, at the
29
+ # pinned commit): publish is sns:Publish on the topic's ARN; subscribe is
30
+ # sns:Subscribe, the API call alone, as the CDK grants it. Under a
31
+ # customer-managed key, publish also grants kms:Decrypt and
32
+ # kms:GenerateDataKey* on the key (grants.json, publish.keyActions), a
33
+ # second statement on the same principal's policy; subscribe grants nothing
34
+ # on the key.
31
35
  class Topic < Construct
32
36
  # The CDK's publish action (topic-base.ts:250).
33
37
  PUBLISH_ACTION = "sns:Publish"
@@ -35,9 +39,12 @@ module RubyCdk
35
39
  # The CDK's subscribe action (topic-base.ts, grantSubscribe).
36
40
  SUBSCRIBE_ACTION = "sns:Subscribe"
37
41
 
38
- attr_reader :fifo
42
+ # The key actions of publish (aws-sns/grants.json, publish.keyActions).
43
+ PUBLISH_KEY_ACTIONS = [ "kms:Decrypt", "kms:GenerateDataKey*" ].freeze
44
+
45
+ attr_reader :fifo, :master_key
39
46
 
40
- def initialize(scope, id, topic_name: nil, display_name: nil, fifo: false, content_based_deduplication: false)
47
+ def initialize(scope, id, topic_name: nil, display_name: nil, fifo: false, content_based_deduplication: false, master_key: nil)
41
48
  super(scope, id)
42
49
  @fifo = fifo ? true : false
43
50
  @topic_name = topic_name.nil? || topic_name.is_a?(String) && !topic_name.empty? ? topic_name :
@@ -49,10 +56,12 @@ module RubyCdk
49
56
  raise UsageError, "#{path}: content_based_deduplication needs a FIFO topic, as in the CDK " \
50
57
  "(its ContentBasedDeduplicationNotAllowedOnStandardTopic)"
51
58
  end
59
+ @master_key = master_key && KMS.key_reference(master_key, "#{path}: master_key")
52
60
 
53
61
  @resource = resource("Resource", "AWS::SNS::Topic",
54
62
  TopicName: @topic_name,
55
63
  DisplayName: display_name,
64
+ KmsMasterKeyId: @master_key && KMS.key_arn(@master_key),
56
65
  FifoTopic: @fifo || nil,
57
66
  ContentBasedDeduplication: content_based_deduplication ? true : nil)
58
67
  end
@@ -74,9 +83,11 @@ module RubyCdk
74
83
  end
75
84
 
76
85
  # Grants the publish action to the principal (topic-base.ts,
77
- # grantPublish).
86
+ # grantPublish), and the key's actions under a customer-managed key.
78
87
  def grant_publish(principal)
79
- Constructs::Grant.add_to_principal(principal, [ PUBLISH_ACTION ], [ arn ])
88
+ grant = Constructs::Grant.add_to_principal(principal, [ PUBLISH_ACTION ], [ arn ])
89
+ KMS.grant_on_key(@master_key, principal, PUBLISH_KEY_ACTIONS) if @master_key
90
+ grant
80
91
  end
81
92
 
82
93
  # Grants the subscribe action (topic-base.ts, grantSubscribe).
@@ -7,7 +7,9 @@
7
7
  #
8
8
  # RubyCdk::S3::Bucket, RubyCdk::IAM::Role, RubyCdk::Lambda::Function,
9
9
  # RubyCdk::DynamoDB::Table, RubyCdk::SQS::Queue, RubyCdk::SNS::Topic,
10
- # RubyCdk::Logs::LogGroup
10
+ # RubyCdk::Logs::LogGroup, RubyCdk::SSM::Parameter,
11
+ # RubyCdk::SecretsManager::Secret, RubyCdk::Events::Rule,
12
+ # RubyCdk::ApiGateway::RestApi, RubyCdk::KMS::Key
11
13
  #
12
14
  # The sources behind the defaults were read in aws/aws-cdk at commit
13
15
  # c070afb54b9e4dbddd52a85a21077fe970354985 (main, read on 2026-11-25,
@@ -26,9 +28,13 @@
26
28
  # statement lands in the principal's own policy through the grantee's
27
29
  # grantPrincipal (Role.grantPrincipal is the role itself, role.ts:462) and
28
30
  # its addToPrincipalPolicy (role.ts:653), which creates the DefaultPolicy
29
- # resource. This tool grants to identities only, so there is no resource
30
- # policy here and no Lambda::Permission: a grant never broadens a
31
- # resource's own policy.
31
+ # resource. A grant_* never broadens a resource's own policy. The
32
+ # resource-policy side - the AWS::Lambda::Permission a service principal
33
+ # that invokes a function itself needs, which cannot carry a statement of
34
+ # its own - is Function#add_permission, the CDK's addPermission
35
+ # (function-base.ts:407), and the constructs that point a service
36
+ # principal at a function wire it (D-020's note of 2026-11-28,
37
+ # architecture section 21).
32
38
  #
33
39
  # Anything where the CDK does differently from the safe defaults of
34
40
  # architecture section 7 is decided for section 7 and listed in architecture
@@ -48,9 +54,15 @@ end
48
54
  require_relative "constructs/policy_statement"
49
55
  require_relative "constructs/grant"
50
56
  require_relative "constructs/role"
57
+ require_relative "constructs/kms_key"
51
58
  require_relative "constructs/bucket"
52
59
  require_relative "constructs/log_group"
53
60
  require_relative "constructs/function"
54
61
  require_relative "constructs/table"
55
62
  require_relative "constructs/queue"
56
63
  require_relative "constructs/topic"
64
+ require_relative "constructs/ssm_parameter"
65
+ require_relative "constructs/secret"
66
+ require_relative "constructs/schedule"
67
+ require_relative "constructs/events_rule"
68
+ require_relative "constructs/restapi"