ruby-cdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +87 -0
  3. data/LICENSE +21 -0
  4. data/README.md +303 -0
  5. data/THIRD_PARTY_NOTICES.md +327 -0
  6. data/data/spec/META.json +33 -0
  7. data/data/spec/model.json.gz +0 -0
  8. data/exe/ruby-cdk +9 -0
  9. data/lib/ruby-cdk.rb +4 -0
  10. data/lib/ruby_cdk/assets/builder.rb +122 -0
  11. data/lib/ruby_cdk/assets/hasher.rb +175 -0
  12. data/lib/ruby_cdk/assets/record.rb +49 -0
  13. data/lib/ruby_cdk/assets/uploader.rb +139 -0
  14. data/lib/ruby_cdk/assets/zipper.rb +108 -0
  15. data/lib/ruby_cdk/assets.rb +116 -0
  16. data/lib/ruby_cdk/bootstrap.rb +289 -0
  17. data/lib/ruby_cdk/cfn/resource.rb +93 -0
  18. data/lib/ruby_cdk/cfn.rb +10 -0
  19. data/lib/ruby_cdk/cli/arguments.rb +41 -0
  20. data/lib/ruby_cdk/cli/aws.rb +35 -0
  21. data/lib/ruby_cdk/cli/bootstrap.rb +63 -0
  22. data/lib/ruby_cdk/cli/diff.rb +98 -0
  23. data/lib/ruby_cdk/cli/failure.rb +80 -0
  24. data/lib/ruby_cdk/cli/io.rb +70 -0
  25. data/lib/ruby_cdk/cli/list.rb +46 -0
  26. data/lib/ruby_cdk/cli/new.rb +313 -0
  27. data/lib/ruby_cdk/cli/operation.rb +124 -0
  28. data/lib/ruby_cdk/cli/pairs.rb +32 -0
  29. data/lib/ruby_cdk/cli/report.rb +118 -0
  30. data/lib/ruby_cdk/cli/selection.rb +134 -0
  31. data/lib/ruby_cdk/cli/session.rb +290 -0
  32. data/lib/ruby_cdk/cli/shell.rb +30 -0
  33. data/lib/ruby_cdk/cli/synth.rb +58 -0
  34. data/lib/ruby_cdk/cli/validate.rb +101 -0
  35. data/lib/ruby_cdk/cli.rb +242 -0
  36. data/lib/ruby_cdk/constructs/bucket.rb +191 -0
  37. data/lib/ruby_cdk/constructs/function.rb +163 -0
  38. data/lib/ruby_cdk/constructs/grant.rb +90 -0
  39. data/lib/ruby_cdk/constructs/log_group.rb +115 -0
  40. data/lib/ruby_cdk/constructs/policy_statement.rb +161 -0
  41. data/lib/ruby_cdk/constructs/queue.rb +118 -0
  42. data/lib/ruby_cdk/constructs/role.rb +282 -0
  43. data/lib/ruby_cdk/constructs/table.rb +160 -0
  44. data/lib/ruby_cdk/constructs/topic.rb +88 -0
  45. data/lib/ruby_cdk/constructs.rb +56 -0
  46. data/lib/ruby_cdk/core/app.rb +146 -0
  47. data/lib/ruby_cdk/core/construct.rb +105 -0
  48. data/lib/ruby_cdk/core/elements.rb +107 -0
  49. data/lib/ruby_cdk/core/ids.rb +117 -0
  50. data/lib/ruby_cdk/core/stack.rb +291 -0
  51. data/lib/ruby_cdk/core/stateful.rb +156 -0
  52. data/lib/ruby_cdk/core.rb +15 -0
  53. data/lib/ruby_cdk/deploy/capabilities.rb +44 -0
  54. data/lib/ruby_cdk/deploy/deployer.rb +805 -0
  55. data/lib/ruby_cdk/deploy/errors.rb +72 -0
  56. data/lib/ruby_cdk/deploy/fakes.rb +546 -0
  57. data/lib/ruby_cdk/deploy/output/base.rb +167 -0
  58. data/lib/ruby_cdk/deploy/output/human.rb +37 -0
  59. data/lib/ruby_cdk/deploy/output/json.rb +80 -0
  60. data/lib/ruby_cdk/deploy/output/quiet.rb +20 -0
  61. data/lib/ruby_cdk/deploy/parameters.rb +86 -0
  62. data/lib/ruby_cdk/deploy/poller.rb +72 -0
  63. data/lib/ruby_cdk/deploy/ports.rb +205 -0
  64. data/lib/ruby_cdk/deploy/sdk_adapters.rb +608 -0
  65. data/lib/ruby_cdk/deploy/states.rb +62 -0
  66. data/lib/ruby_cdk/deploy.rb +25 -0
  67. data/lib/ruby_cdk/diff/compare.rb +141 -0
  68. data/lib/ruby_cdk/diff/normalizer.rb +83 -0
  69. data/lib/ruby_cdk/diff/render.rb +242 -0
  70. data/lib/ruby_cdk/diff/security.rb +322 -0
  71. data/lib/ruby_cdk/diff/statement.rb +256 -0
  72. data/lib/ruby_cdk/diff/template.rb +524 -0
  73. data/lib/ruby_cdk/diff.rb +62 -0
  74. data/lib/ruby_cdk/env.rb +42 -0
  75. data/lib/ruby_cdk/errors.rb +38 -0
  76. data/lib/ruby_cdk/fn.rb +409 -0
  77. data/lib/ruby_cdk/lazy.rb +55 -0
  78. data/lib/ruby_cdk/nag/config.rb +303 -0
  79. data/lib/ruby_cdk/nag/engine.rb +152 -0
  80. data/lib/ruby_cdk/nag/report.rb +86 -0
  81. data/lib/ruby_cdk/nag/rule.rb +171 -0
  82. data/lib/ruby_cdk/nag/rules/api_gateway_authorization.rb +91 -0
  83. data/lib/ruby_cdk/nag/rules/dynamodb_point_in_time_recovery.rb +45 -0
  84. data/lib/ruby_cdk/nag/rules/ebs_volume_encrypted.rb +41 -0
  85. data/lib/ruby_cdk/nag/rules/ec2_ingress_http.rb +48 -0
  86. data/lib/ruby_cdk/nag/rules/ec2_ingress_other_ports.rb +46 -0
  87. data/lib/ruby_cdk/nag/rules/iam_policy_admin_access.rb +60 -0
  88. data/lib/ruby_cdk/nag/rules/iam_policy_full_access.rb +55 -0
  89. data/lib/ruby_cdk/nag/rules/iam_user_credentials.rb +61 -0
  90. data/lib/ruby_cdk/nag/rules/lambda_runtime_supported.rb +88 -0
  91. data/lib/ruby_cdk/nag/rules/lambda_secret_environment.rb +61 -0
  92. data/lib/ruby_cdk/nag/rules/log_group_retention.rb +40 -0
  93. data/lib/ruby_cdk/nag/rules/policy_statements.rb +128 -0
  94. data/lib/ruby_cdk/nag/rules/rds_storage_encrypted.rb +65 -0
  95. data/lib/ruby_cdk/nag/rules/resource_policy_wildcard_principal.rb +58 -0
  96. data/lib/ruby_cdk/nag/rules/s3_public_access_block.rb +56 -0
  97. data/lib/ruby_cdk/nag/rules/security_group_ingress.rb +136 -0
  98. data/lib/ruby_cdk/nag/rules/stateful_deletion_policy.rb +46 -0
  99. data/lib/ruby_cdk/nag/rules.rb +51 -0
  100. data/lib/ruby_cdk/nag/values.rb +305 -0
  101. data/lib/ruby_cdk/nag.rb +60 -0
  102. data/lib/ruby_cdk/schema/normalizer.rb +164 -0
  103. data/lib/ruby_cdk/schema/property_schema.rb +22 -0
  104. data/lib/ruby_cdk/schema/schema.rb +195 -0
  105. data/lib/ruby_cdk/schema/sources/compiler.rb +56 -0
  106. data/lib/ruby_cdk/schema/sources/descriptor.rb +21 -0
  107. data/lib/ruby_cdk/schema/sources/download.rb +86 -0
  108. data/lib/ruby_cdk/schema/sources/provider_schemas.rb +47 -0
  109. data/lib/ruby_cdk/schema/sources/provider_type.rb +630 -0
  110. data/lib/ruby_cdk/schema/sources/regions.rb +86 -0
  111. data/lib/ruby_cdk/schema/sources/resource_specification.rb +94 -0
  112. data/lib/ruby_cdk/schema/sources/specification_type.rb +159 -0
  113. data/lib/ruby_cdk/schema/sources/update.rb +178 -0
  114. data/lib/ruby_cdk/schema/sources.rb +20 -0
  115. data/lib/ruby_cdk/schema/type_schema.rb +109 -0
  116. data/lib/ruby_cdk/schema/validator/corpus_check.rb +81 -0
  117. data/lib/ruby_cdk/schema/validator/policies.rb +48 -0
  118. data/lib/ruby_cdk/schema/validator/refs.rb +489 -0
  119. data/lib/ruby_cdk/schema/validator/report.rb +92 -0
  120. data/lib/ruby_cdk/schema/validator/rule.rb +119 -0
  121. data/lib/ruby_cdk/schema/validator/scans.rb +146 -0
  122. data/lib/ruby_cdk/schema/validator/structure.rb +469 -0
  123. data/lib/ruby_cdk/schema/validator/template.rb +203 -0
  124. data/lib/ruby_cdk/schema/validator/template_rules.rb +70 -0
  125. data/lib/ruby_cdk/schema/validator/walk.rb +122 -0
  126. data/lib/ruby_cdk/schema/validator.rb +159 -0
  127. data/lib/ruby_cdk/schema.rb +19 -0
  128. data/lib/ruby_cdk/synth/manifest.rb +128 -0
  129. data/lib/ruby_cdk/synth/resolver.rb +326 -0
  130. data/lib/ruby_cdk/synth/rules.rb +83 -0
  131. data/lib/ruby_cdk/synth/serializer.rb +120 -0
  132. data/lib/ruby_cdk/synth/writer.rb +31 -0
  133. data/lib/ruby_cdk/synth.rb +255 -0
  134. data/lib/ruby_cdk/test/capture.rb +133 -0
  135. data/lib/ruby_cdk/test/match.rb +426 -0
  136. data/lib/ruby_cdk/test/matcher.rb +290 -0
  137. data/lib/ruby_cdk/test/private/absent.rb +34 -0
  138. data/lib/ruby_cdk/test/private/conditions.rb +39 -0
  139. data/lib/ruby_cdk/test/private/cyclic.rb +160 -0
  140. data/lib/ruby_cdk/test/private/error.rb +48 -0
  141. data/lib/ruby_cdk/test/private/js.rb +326 -0
  142. data/lib/ruby_cdk/test/private/mappings.rb +39 -0
  143. data/lib/ruby_cdk/test/private/outputs.rb +39 -0
  144. data/lib/ruby_cdk/test/private/parameters.rb +39 -0
  145. data/lib/ruby_cdk/test/private/resources.rb +116 -0
  146. data/lib/ruby_cdk/test/private/section.rb +98 -0
  147. data/lib/ruby_cdk/test/private/sorting.rb +40 -0
  148. data/lib/ruby_cdk/test/private/sparse_matrix.rb +35 -0
  149. data/lib/ruby_cdk/test/private/type.rb +23 -0
  150. data/lib/ruby_cdk/test/template.rb +364 -0
  151. data/lib/ruby_cdk/test.rb +116 -0
  152. data/lib/ruby_cdk/values.rb +8 -0
  153. data/lib/ruby_cdk/version.rb +5 -0
  154. data/lib/ruby_cdk.rb +47 -0
  155. metadata +256 -0
@@ -0,0 +1,282 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+ require_relative "../fn"
5
+ require_relative "../lazy"
6
+ require_relative "policy_statement"
7
+ require_relative "grant"
8
+
9
+ module RubyCdk
10
+ module IAM
11
+ # An IAM role: the port of the CDK's Role (aws-iam/lib/role.ts), read at
12
+ # commit c070afb54b9e4dbddd52a85a21077fe970354985, Apache-2.0.
13
+ #
14
+ # RubyCdk::IAM::Role.new(stack, "Role",
15
+ # assumed_by: "lambda.amazonaws.com",
16
+ # managed_policy_arns: ["arn:aws:iam::aws:policy/ReadOnlyAccess"])
17
+ #
18
+ # `assumed_by` builds the AssumeRolePolicyDocument (role.ts,
19
+ # createAssumeRolePolicy): one Allow statement per principal, Action
20
+ # "sts:AssumeRole". A principal is a service name ("lambda.amazonaws.com"
21
+ # becomes Service), an ARN or an account id (both become AWS, as written),
22
+ # "*" (AnyPrincipal, which the CDK writes as { AWS: "*" } in a trust
23
+ # policy), a Hash taken verbatim, or a list of any of these (the CDK's
24
+ # CompositePrincipal, one statement each).
25
+ #
26
+ # Statements join the role's policy the CDK's ways (role.ts:653-661,
27
+ # addToPrincipalPolicy):
28
+ #
29
+ # - add_to_policy(statement) and attach_policy(statement) - the same
30
+ # thing, both named after how they are read - create or extend the
31
+ # role's DefaultPolicy resource, an AWS::IAM::Policy whose logical ID
32
+ # is the role's with DefaultPolicy behind it and whose PolicyName is
33
+ # that logical ID, as the CDK's generatePolicyName takes the logical ID
34
+ # (aws-iam/lib/private/util.ts). The statements sit behind a Lazy, so
35
+ # grants applied after the role was built are all there.
36
+ # - to_inline_policy(statements, name:) writes a named policy into the
37
+ # role's Policies list, the CDK's inlinePolicies prop (role.ts:112).
38
+ #
39
+ # The grant_* friends make the role the principal other constructs grant
40
+ # to, the CDK's IGrantable (role.ts:462, grantPrincipal = this):
41
+ # grant(principal, ...actions) is the CDK's Role#grant - the actions on the
42
+ # role's ARN - and grant_pass_role and grant_assume_role its two named
43
+ # ones (role.ts:704-732).
44
+ #
45
+ # Used twice in one stack, each role carries its own Resource and
46
+ # DefaultPolicy under its own logical ID.
47
+ class Role < Construct
48
+ # The CDK's rule for a role name (role.ts, InvalidRoleName): IAM's own.
49
+ ROLE_NAME_PATTERN = /\A[\w+=,.@-]{1,64}\z/
50
+
51
+ # The CDK's bounds for maxSessionDuration (role.ts, validateMaxSessionDuration).
52
+ MIN_SESSION_DURATION = 3600
53
+ MAX_SESSION_DURATION = 43_200
54
+
55
+ # The CDK's bound for the description (role.ts, RoleDescriptionLongerCharacters).
56
+ MAX_DESCRIPTION_LENGTH = 1000
57
+
58
+ # The action of every trust policy.
59
+ ASSUME_ROLE_ACTION = "sts:AssumeRole"
60
+
61
+ attr_reader :assumed_by, :managed_policy_arns
62
+
63
+ def initialize(scope, id, assumed_by:, managed_policy_arns: [], role_name: nil, description: nil, max_session_duration: nil)
64
+ super(scope, id)
65
+ @assumed_by = assumed_by
66
+ @role_name = valid_role_name(role_name)
67
+ @description = valid_description(description)
68
+ @session_duration = valid_session_duration(max_session_duration)
69
+ @statements = []
70
+ @inline_policies = {}
71
+ @policy = nil
72
+
73
+ # Managed policy ARNs can be added after the role was built, so the
74
+ # property reads them when the stack is resolved.
75
+ @managed_policy_arns = []
76
+ managed_policy_arns.each { |arn| add_managed_policy(arn) }
77
+
78
+ @resource = resource("Resource", "AWS::IAM::Role",
79
+ AssumeRolePolicyDocument: assume_role_policy_document,
80
+ ManagedPolicyArns: Lazy.new { @managed_policy_arns.empty? ? nil : @managed_policy_arns },
81
+ Policies: Lazy.new { inline_policies_property },
82
+ RoleName: @role_name,
83
+ MaxSessionDuration: @session_duration,
84
+ Description: @description)
85
+ end
86
+
87
+ # The logical ID of the AWS::IAM::Role under this construct, so that the
88
+ # role can sit in another resource's depends_on:.
89
+ def logical_id
90
+ @resource.logical_id
91
+ end
92
+
93
+ # The role's ARN.
94
+ def arn
95
+ Fn.get_att(@resource, "Arn")
96
+ end
97
+
98
+ alias principal_arn arn
99
+
100
+ # The role's name: the one given, or the Ref of the resource.
101
+ def role_name
102
+ @role_name || Fn.ref(@resource)
103
+ end
104
+
105
+ # This role is what other constructs' grant_* grant to: the CDK's
106
+ # IGrantable (role.ts:462, grantPrincipal = this).
107
+ def grant_principal
108
+ self
109
+ end
110
+
111
+ # Adds a statement to the role's DefaultPolicy, creating it on the first
112
+ # call (role.ts:653-661). statement is an IAM::PolicyStatement or a Hash
113
+ # in CloudFormation's statement shape.
114
+ #
115
+ # attach_policy is the same method under its other name.
116
+ def add_to_policy(statement)
117
+ @statements << as_statement(statement)
118
+ @policy ||= resource("DefaultPolicy", "AWS::IAM::Policy",
119
+ PolicyDocument: Lazy.new { policy_document(@statements) },
120
+ PolicyName: Lazy.new { policy_name },
121
+ Roles: [ Fn.ref(@resource) ])
122
+ self
123
+ end
124
+
125
+ alias attach_policy add_to_policy
126
+
127
+ # Writes a named inline policy into the role's Policies list, the CDK's
128
+ # inlinePolicies prop (role.ts:112, _flatten at :594): one
129
+ # { PolicyName, PolicyDocument } per name. A name used twice is refused,
130
+ # as two attached policies of one name are in the CDK
131
+ # (aws-iam/lib/private/util.ts, PolicyNamedAlreadyAttached).
132
+ def to_inline_policy(statements, name:)
133
+ unless name.is_a?(String) && !name.empty?
134
+ raise UsageError, "#{path}: to_inline_policy takes a name:, got #{name.inspect}"
135
+ end
136
+ if @inline_policies.key?(name)
137
+ raise UsageError, "#{path}: there is already an inline policy named #{name.inspect} on this role"
138
+ end
139
+
140
+ list = Array(statements).map { |statement| as_statement(statement) }
141
+ raise UsageError, "#{path}: to_inline_policy takes at least one statement" if list.empty?
142
+
143
+ @inline_policies[name] = list
144
+ self
145
+ end
146
+
147
+ # Adds a managed policy ARN, later included; the same ARN twice adds
148
+ # nothing, as the CDK's UniqueStringSet dedupes (role.ts:601).
149
+ def add_managed_policy(arn)
150
+ unless arn.is_a?(String) && !arn.empty?
151
+ raise UsageError, "#{path}: add_managed_policy takes a policy ARN, got #{arn.inspect}"
152
+ end
153
+
154
+ @managed_policy_arns << arn unless @managed_policy_arns.include?(arn)
155
+ self
156
+ end
157
+
158
+ # Grants the actions on this role's ARN to the principal: the CDK's
159
+ # Role#grant (role.ts:704-711).
160
+ def grant(principal, *actions)
161
+ Constructs::Grant.add_to_principal(principal, actions, [ arn ])
162
+ end
163
+
164
+ # Grants iam:PassRole on this role to the principal (role.ts:716-721).
165
+ def grant_pass_role(principal)
166
+ grant(principal, "iam:PassRole")
167
+ end
168
+
169
+ # Grants sts:AssumeRole on this role to the principal (role.ts:726-732).
170
+ # A service or account principal cannot assume a role this way - the CDK
171
+ # refuses one with "use assumeRolePolicy instead", and so does this.
172
+ def grant_assume_role(principal)
173
+ unless assumable_principal?(principal)
174
+ raise UsageError,
175
+ "Cannot use a service or account principal with grant_assume_role, use the assume_role_policy instead " \
176
+ "(give assumed_by: to a new role, or grant a principal named by its ARN)"
177
+ end
178
+
179
+ grant(principal, ASSUME_ROLE_ACTION)
180
+ end
181
+
182
+ private
183
+
184
+ def valid_role_name(name)
185
+ return nil if name.nil?
186
+ return name if name.is_a?(String) && name.match?(ROLE_NAME_PATTERN)
187
+
188
+ raise UsageError, "#{path}: the role name must be 1 to 64 characters of letters, digits and _+=,.@-, got #{name.inspect}"
189
+ end
190
+
191
+ def valid_description(description)
192
+ return nil if description.nil? || (description.is_a?(String) && description.empty?)
193
+ return description if description.is_a?(String) && description.length <= MAX_DESCRIPTION_LENGTH
194
+
195
+ raise UsageError, "#{path}: the description must be at most #{MAX_DESCRIPTION_LENGTH} characters, got #{description.inspect}"
196
+ end
197
+
198
+ def valid_session_duration(duration)
199
+ return nil if duration.nil?
200
+ return duration if duration.is_a?(Integer) && duration.between?(MIN_SESSION_DURATION, MAX_SESSION_DURATION)
201
+
202
+ raise UsageError, "#{path}: max_session_duration is set to #{duration.inspect}, but must be between " \
203
+ "#{MIN_SESSION_DURATION} (1h) and #{MAX_SESSION_DURATION} (12h) seconds"
204
+ end
205
+
206
+ def as_statement(statement)
207
+ return statement if statement.is_a?(PolicyStatement)
208
+ return statement if statement.is_a?(Hash)
209
+
210
+ raise UsageError, "#{path}: a policy statement is an IAM::PolicyStatement or a Hash in CloudFormation's shape, got #{statement.inspect}"
211
+ end
212
+
213
+ # The statement as the template holds it: a PolicyStatement renders
214
+ # itself, a Hash is taken verbatim with its keys as the user wrote them.
215
+ def statement_rendered(statement)
216
+ return statement.to_statement if statement.is_a?(PolicyStatement)
217
+
218
+ statement.to_h { |key, value| [ key.to_s, value ] }
219
+ end
220
+
221
+ # One Allow statement per principal, the CDK's trust policy
222
+ # (createAssumeRolePolicy, role.ts:881-894; its CompositePrincipal test).
223
+ def assume_role_policy_document
224
+ {
225
+ "Version" => "2012-10-17",
226
+ "Statement" => assumed_by_principals.map { |principal| assume_statement(principal).to_statement }
227
+ }
228
+ end
229
+
230
+ def assumed_by_principals
231
+ list = @assumed_by.is_a?(Array) ? @assumed_by : [ @assumed_by ]
232
+ raise UsageError, "#{path}: assumed_by takes a principal or a list of them, got #{@assumed_by.inspect}" if list.empty?
233
+
234
+ list.map { |principal| principal.is_a?(Hash) ? stringify_keys(principal) : principal }
235
+ end
236
+
237
+ def assume_statement(principal)
238
+ IAM::PolicyStatement.new(
239
+ actions: [ ASSUME_ROLE_ACTION ],
240
+ # The CDK writes AnyPrincipal in a trust policy as { AWS: "*" }
241
+ # (role.ts, its "Principal-* gets translated" test): a bare "*" is
242
+ # refused by CreateRole there.
243
+ principals: principal == "*" ? { "AWS" => "*" } : principal
244
+ )
245
+ end
246
+
247
+ def stringify_keys(hash)
248
+ hash.to_h { |key, value| [ key.to_s, value ] }
249
+ end
250
+
251
+ # The DefaultPolicy's document, once the statements are in.
252
+ def policy_document(statements)
253
+ { "Version" => "2012-10-17", "Statement" => statements.map { |statement| statement_rendered(statement) } }
254
+ end
255
+
256
+ # The CDK names an inline policy after its logical ID, last 128
257
+ # characters (aws-iam/lib/private/util.ts, generatePolicyName).
258
+ def policy_name
259
+ logical = @policy.logical_id
260
+ logical.length > 128 ? logical[-128..] : logical
261
+ end
262
+
263
+ def inline_policies_property
264
+ return nil if @inline_policies.empty?
265
+
266
+ @inline_policies.map do |name, statements|
267
+ { "PolicyName" => name, "PolicyDocument" => policy_document(statements) }
268
+ end
269
+ end
270
+
271
+ # A principal that can be granted sts:AssumeRole on: an IAM::Role, or an
272
+ # ARN. A service name or an account id is refused (role.ts, its two
273
+ # "cannot grant AssumeRole" tests).
274
+ def assumable_principal?(principal)
275
+ return true if principal.is_a?(IAM::Role)
276
+ return principal.is_a?(String) && principal.start_with?("arn:") if principal.is_a?(String)
277
+
278
+ false
279
+ end
280
+ end
281
+ end
282
+ end
@@ -0,0 +1,160 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+ require_relative "../fn"
5
+ require_relative "grant"
6
+
7
+ module RubyCdk
8
+ module DynamoDB
9
+ # A DynamoDB table: the port of the CDK's Table (aws-dynamodb/lib/table.ts),
10
+ # read at commit c070afb54b9e4dbddd52a85a21077fe970354985, Apache-2.0.
11
+ #
12
+ # RubyCdk::DynamoDB::Table.new(stack, "Table",
13
+ # partition_key: { name: "id", type: :string },
14
+ # sort_key: { name: "sk", type: :number })
15
+ #
16
+ # Defaults, and where they differ from the CDK (architecture section 7
17
+ # wins; the rows are in section 21):
18
+ #
19
+ # - Billing is on demand: BillingMode PAY_PER_REQUEST, the plan's default
20
+ # for a small project, where the CDK's default is provisioned with 5
21
+ # read and 5 write units (table.ts:1347). billing: :provisioned writes
22
+ # ProvisionedThroughput with the capacities given, 5 and 5 when none
23
+ # are.
24
+ # - Point-in-time recovery is on: PointInTimeRecoverySpecification with
25
+ # PointInTimeRecoveryEnabled true, the nag rule for a table without it
26
+ # being a medium. The CDK writes no specification at all, which leaves
27
+ # recovery off. point_in_time_recovery: false writes the specification
28
+ # with false, as the CDK's pointInTimeRecovery: false does.
29
+ # - The table is a retained type (architecture section 7), which the
30
+ # synthesis gives every AWS::DynamoDB::Table.
31
+ #
32
+ # Key attributes take their type as a Symbol (:string, :number, :binary)
33
+ # or as DynamoDB's own letter ("S", "N", "B").
34
+ #
35
+ # The grants are the CDK's (aws-dynamodb/lib/table-grants.ts and perms.ts,
36
+ # at the same commit): grant_read_data is the read actions and
37
+ # DescribeTable, grant_read_write_data adds the write ones, each one
38
+ # statement on the table's ARN - the CDK grants the same set as two
39
+ # statements that its policy document minimizes into one, and this tool
40
+ # writes the one. grant_full_access is dynamodb:*, and grant takes any
41
+ # actions given.
42
+ class Table < Construct
43
+ # The CDK's data read actions, then DescribeTable, in the order its
44
+ # minimized statement carries (table-grants.ts, readData; its test).
45
+ READ_DATA_ACTIONS = [
46
+ "dynamodb:BatchGetItem", "dynamodb:GetRecords", "dynamodb:GetShardIterator",
47
+ "dynamodb:Query", "dynamodb:GetItem", "dynamodb:Scan", "dynamodb:ConditionCheckItem",
48
+ "dynamodb:DescribeTable"
49
+ ].freeze
50
+
51
+ # readWriteData: the read actions, then the write ones, then
52
+ # DescribeTable, in the CDK's order.
53
+ READ_WRITE_DATA_ACTIONS = [
54
+ "dynamodb:BatchGetItem", "dynamodb:GetRecords", "dynamodb:GetShardIterator",
55
+ "dynamodb:Query", "dynamodb:GetItem", "dynamodb:Scan", "dynamodb:ConditionCheckItem",
56
+ "dynamodb:BatchWriteItem", "dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:DeleteItem",
57
+ "dynamodb:DescribeTable"
58
+ ].freeze
59
+
60
+ # The CDK's AttributeType names.
61
+ ATTRIBUTE_TYPES = { string: "S", number: "N", binary: "B" }.freeze
62
+
63
+ # The CDK's default provisioned capacities (table.ts:1372).
64
+ DEFAULT_CAPACITY = 5
65
+
66
+ attr_reader :partition_key, :sort_key, :billing
67
+
68
+ 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)
70
+ super(scope, id)
71
+ @partition_key = attribute(partition_key, "partition_key")
72
+ @sort_key = sort_key && attribute(sort_key, "sort_key")
73
+ @table_name = table_name.nil? || table_name.is_a?(String) && !table_name.empty? ? table_name :
74
+ raise(UsageError, "#{path}: table_name must be a non-empty String, got #{table_name.inspect}")
75
+ @billing = billing == :on_demand || billing == :provisioned ? billing :
76
+ raise(UsageError, "#{path}: billing takes :on_demand or :provisioned, got #{billing.inspect}")
77
+ @pitr = point_in_time_recovery == true || point_in_time_recovery == false ? point_in_time_recovery :
78
+ raise(UsageError, "#{path}: point_in_time_recovery takes true or false, got #{point_in_time_recovery.inspect}")
79
+
80
+ # Grown with pushes rather than a literal of one, so that the key types
81
+ # stay plain Strings for the checker.
82
+ schema = []
83
+ schema << { "AttributeName" => @partition_key[:name], "KeyType" => "HASH" }
84
+ definitions = []
85
+ definitions << { "AttributeName" => @partition_key[:name], "AttributeType" => @partition_key[:type] }
86
+ if @sort_key
87
+ schema << { "AttributeName" => @sort_key[:name], "KeyType" => "RANGE" }
88
+ definitions << { "AttributeName" => @sort_key[:name], "AttributeType" => @sort_key[:type] }
89
+ end
90
+
91
+ @resource = resource("Resource", "AWS::DynamoDB::Table",
92
+ TableName: @table_name,
93
+ AttributeDefinitions: definitions,
94
+ KeySchema: schema,
95
+ BillingMode: @billing == :on_demand ? "PAY_PER_REQUEST" : nil,
96
+ ProvisionedThroughput: @billing == :provisioned ?
97
+ {
98
+ "ReadCapacityUnits" => read_capacity || DEFAULT_CAPACITY,
99
+ "WriteCapacityUnits" => write_capacity || DEFAULT_CAPACITY
100
+ } : nil,
101
+ PointInTimeRecoverySpecification: { "PointInTimeRecoveryEnabled" => @pitr })
102
+ end
103
+
104
+ # The logical ID of the AWS::DynamoDB::Table under this construct, so
105
+ # that the table can sit in another resource's depends_on:.
106
+ def logical_id
107
+ @resource.logical_id
108
+ end
109
+
110
+ # The table's ARN.
111
+ def arn
112
+ Fn.get_att(@resource, "Arn")
113
+ end
114
+
115
+ # The table's name: the one given, or the Ref of the resource.
116
+ def table_name
117
+ @table_name || Fn.ref(@resource)
118
+ end
119
+
120
+ # Permits all data read operations from this table: the CDK's
121
+ # grantReadData (table-grants.ts, readData, its minimized statement).
122
+ def grant_read_data(principal)
123
+ Constructs::Grant.add_to_principal(principal, READ_DATA_ACTIONS, [ arn ])
124
+ end
125
+
126
+ # Permits all data read and write operations: the CDK's
127
+ # grantReadWriteData (table-grants.ts, readWriteData).
128
+ def grant_read_write_data(principal)
129
+ Constructs::Grant.add_to_principal(principal, READ_WRITE_DATA_ACTIONS, [ arn ])
130
+ end
131
+
132
+ # Permits every operation on the table: the CDK's grantFullAccess.
133
+ def grant_full_access(principal)
134
+ Constructs::Grant.add_to_principal(principal, [ "dynamodb:*" ], [ arn ])
135
+ end
136
+
137
+ # Grants the actions given, as the CDK's grant does (table-grants.ts,
138
+ # actions).
139
+ def grant(principal, *actions)
140
+ Constructs::Grant.add_to_principal(principal, actions, [ arn ])
141
+ end
142
+
143
+ private
144
+
145
+ # { name:, type: } with the type as a Symbol or DynamoDB's letter.
146
+ def attribute(key, what)
147
+ unless key.is_a?(Hash) && key[:name].is_a?(String) && !key[:name].empty?
148
+ raise UsageError, "#{path}: #{what} takes { name:, type: }, got #{key.inspect}"
149
+ end
150
+
151
+ type = ATTRIBUTE_TYPES[key[:type]] || key[:type]
152
+ unless type.is_a?(String) && %w[S N B].include?(type)
153
+ raise UsageError, "#{path}: #{what}'s type takes :string, :number, :binary, \"S\", \"N\" or \"B\", got #{key[:type].inspect}"
154
+ end
155
+
156
+ { name: key[:name], type: type }
157
+ end
158
+ end
159
+ end
160
+ end
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+ require_relative "../fn"
5
+ require_relative "grant"
6
+
7
+ module RubyCdk
8
+ module SNS
9
+ # An SNS topic: the port of the CDK's Topic (aws-sns/lib/topic.ts), read
10
+ # at commit c070afb54b9e4dbddd52a85a21077fe970354985, Apache-2.0.
11
+ #
12
+ # RubyCdk::SNS::Topic.new(stack, "Events",
13
+ # topic_name: "events", display_name: "Domain events")
14
+ #
15
+ # fifo: true marks the topic FIFO and names it with the .fifo suffix, as
16
+ # the CDK's naming rule does; content_based_deduplication needs a FIFO
17
+ # topic, and is refused on a standard one, as in the CDK. A topic is not a
18
+ # retained type (architecture section 7).
19
+ #
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.
23
+ #
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.
31
+ class Topic < Construct
32
+ # The CDK's publish action (topic-base.ts:250).
33
+ PUBLISH_ACTION = "sns:Publish"
34
+
35
+ # The CDK's subscribe action (topic-base.ts, grantSubscribe).
36
+ SUBSCRIBE_ACTION = "sns:Subscribe"
37
+
38
+ attr_reader :fifo
39
+
40
+ def initialize(scope, id, topic_name: nil, display_name: nil, fifo: false, content_based_deduplication: false)
41
+ super(scope, id)
42
+ @fifo = fifo ? true : false
43
+ @topic_name = topic_name.nil? || topic_name.is_a?(String) && !topic_name.empty? ? topic_name :
44
+ raise(UsageError, "#{path}: topic_name must be a non-empty String, got #{topic_name.inspect}")
45
+ if @topic_name && @fifo && !@topic_name.end_with?(".fifo")
46
+ @topic_name = "#{@topic_name}.fifo"
47
+ end
48
+ if content_based_deduplication && !@fifo
49
+ raise UsageError, "#{path}: content_based_deduplication needs a FIFO topic, as in the CDK " \
50
+ "(its ContentBasedDeduplicationNotAllowedOnStandardTopic)"
51
+ end
52
+
53
+ @resource = resource("Resource", "AWS::SNS::Topic",
54
+ TopicName: @topic_name,
55
+ DisplayName: display_name,
56
+ FifoTopic: @fifo || nil,
57
+ ContentBasedDeduplication: content_based_deduplication ? true : nil)
58
+ end
59
+
60
+ # The logical ID of the AWS::SNS::Topic under this construct, so that the
61
+ # topic can sit in another resource's depends_on:.
62
+ def logical_id
63
+ @resource.logical_id
64
+ end
65
+
66
+ # The topic's ARN: SNS's attribute is TopicArn, not Arn.
67
+ def arn
68
+ Fn.get_att(@resource, "TopicArn")
69
+ end
70
+
71
+ # The topic's name: the one given, or the Ref of the resource.
72
+ def topic_name
73
+ @topic_name || Fn.ref(@resource)
74
+ end
75
+
76
+ # Grants the publish action to the principal (topic-base.ts,
77
+ # grantPublish).
78
+ def grant_publish(principal)
79
+ Constructs::Grant.add_to_principal(principal, [ PUBLISH_ACTION ], [ arn ])
80
+ end
81
+
82
+ # Grants the subscribe action (topic-base.ts, grantSubscribe).
83
+ def grant_subscribe(principal)
84
+ Constructs::Grant.add_to_principal(principal, [ SUBSCRIBE_ACTION ], [ arn ])
85
+ end
86
+ end
87
+ end
88
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The curated L2 constructs (architecture section 3): one class per service,
4
+ # directly under RubyCdk, each building its L1 resources through
5
+ # Construct#resource, under the logical ID derivation of architecture section 3,
6
+ # so that a construct can be used twice in one stack.
7
+ #
8
+ # RubyCdk::S3::Bucket, RubyCdk::IAM::Role, RubyCdk::Lambda::Function,
9
+ # RubyCdk::DynamoDB::Table, RubyCdk::SQS::Queue, RubyCdk::SNS::Topic,
10
+ # RubyCdk::Logs::LogGroup
11
+ #
12
+ # The sources behind the defaults were read in aws/aws-cdk at commit
13
+ # c070afb54b9e4dbddd52a85a21077fe970354985 (main, read on 2026-11-25,
14
+ # Apache-2.0); each construct file names the file it was read from.
15
+ #
16
+ # Two rules the whole directory shares:
17
+ #
18
+ # - Building is immediate (architecture section 3): every L1 resource a
19
+ # construct owns is registered in the tree while its constructor runs.
20
+ # Values that grow after the resource exists - the statements of a role's
21
+ # policy, managed policy ARNs added later - sit behind a Lazy, which
22
+ # synthesis resolves once.
23
+ # - A grant_* method answers a Constructs::Grant and, when the principal can
24
+ # carry one, applies it: Grant.add_to_principal is the port of the CDK's
25
+ # iam.Grant.addToPrincipal (aws-iam/lib/grant.ts, addToPrincipal), whose
26
+ # statement lands in the principal's own policy through the grantee's
27
+ # grantPrincipal (Role.grantPrincipal is the role itself, role.ts:462) and
28
+ # 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.
32
+ #
33
+ # Anything where the CDK does differently from the safe defaults of
34
+ # architecture section 7 is decided for section 7 and listed in architecture
35
+ # section 21; each construct file states its own choices.
36
+
37
+ require_relative "errors"
38
+ require_relative "values"
39
+ require_relative "core"
40
+ require_relative "cfn"
41
+
42
+ module RubyCdk
43
+ # What the curated constructs share: the Grant a grant_* method answers.
44
+ module Constructs
45
+ end
46
+ end
47
+
48
+ require_relative "constructs/policy_statement"
49
+ require_relative "constructs/grant"
50
+ require_relative "constructs/role"
51
+ require_relative "constructs/bucket"
52
+ require_relative "constructs/log_group"
53
+ require_relative "constructs/function"
54
+ require_relative "constructs/table"
55
+ require_relative "constructs/queue"
56
+ require_relative "constructs/topic"