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
@@ -41,11 +41,16 @@ module RubyCdk
41
41
  # - The function resource depends on the role resource as well
42
42
  # (function.ts, this.resource.node.addDependency(this.role)).
43
43
  #
44
- # grant_invoke is the CDK's grantInvoke (aws-lambda/lib/function-base.ts):
45
- # lambda:InvokeFunction on the function's ARN, applied to the principal's
46
- # own policy. The CDK instead adds a Lambda::Permission to the function's
47
- # resource policy; this tool grants to identities only, so the statement
48
- # lands on the caller's role - the same permission, from the other side.
44
+ # Two permission sides, as the CDK has two. grant_invoke is the CDK's
45
+ # grantInvoke (aws-lambda/lib/function-base.ts): lambda:InvokeFunction on
46
+ # the function's ARN, applied to the principal's own policy - the
47
+ # identity-based side. add_permission is the CDK's addPermission
48
+ # (function-base.ts:407, the CfnPermission it creates at :424, the props in
49
+ # permission.ts): an AWS::Lambda::Permission under the function's logical
50
+ # id, the resource-policy side a service principal needs, because a service
51
+ # principal that invokes the function itself - API Gateway, EventBridge -
52
+ # carries no policy of its own (proven on the 2026-11-27 sandbox run,
53
+ # where a proxied endpoint 500'd without it; D-020's note).
49
54
  class Function < Construct
50
55
  # The runtime identifier the examples pin. Dated: 2026-11-26, from AWS's
51
56
  # supported-runtimes page. No enum, by design - pass runtime: to move.
@@ -111,11 +116,31 @@ module RubyCdk
111
116
 
112
117
  # Grants lambda:InvokeFunction on this function's ARN to the principal
113
118
  # (function-base.ts, grantInvoke): on the qualified ARN and on the
114
- # unqualified one, as the CDK grants both.
119
+ # unqualified one, as the CDK grants both. The statement lands on the
120
+ # principal's own policy - the identity-based side.
115
121
  def grant_invoke(principal)
116
122
  Constructs::Grant.add_to_principal(principal, [ INVOKE_ACTION ], [ qualified_arn, arn ])
117
123
  end
118
124
 
125
+ # Writes a resource policy statement on the function: the CDK's
126
+ # addPermission (function-base.ts:407-432), one AWS::Lambda::Permission
127
+ # whose FunctionName is the function's ARN, as the CDK passes functionArn
128
+ # there. The resource sits in this function's logical-id namespace under
129
+ # the id given (D-029), so two constructs that wire the same function
130
+ # pass ids that differ - the rule's or the API's. principal is the
131
+ # service principal or ARN as it is written ("apigateway.amazonaws.com");
132
+ # action defaults to the CDK's lambda:InvokeFunction; source_arn and
133
+ # source_account narrow the statement to a caller (the CDK's sourceArn
134
+ # and sourceAccount).
135
+ def add_permission(id, principal:, action: INVOKE_ACTION, source_arn: nil, source_account: nil)
136
+ resource(id, "AWS::Lambda::Permission",
137
+ Action: valid_action(action),
138
+ FunctionName: arn,
139
+ Principal: valid_principal(principal),
140
+ SourceArn: valid_source_arn(source_arn),
141
+ SourceAccount: valid_source_account(source_account))
142
+ end
143
+
119
144
  private
120
145
 
121
146
  def valid_runtime(runtime)
@@ -124,6 +149,40 @@ module RubyCdk
124
149
  raise UsageError, "#{path}: the runtime must be an identifier String such as \"#{DEFAULT_RUNTIME}\", got #{runtime.inspect}"
125
150
  end
126
151
 
152
+ def valid_action(action)
153
+ return action if action.is_a?(String) && !action.empty?
154
+
155
+ raise UsageError, "#{path}: the action must be an identifier String such as \"#{INVOKE_ACTION}\", got #{action.inspect}"
156
+ end
157
+
158
+ # The principal as it is written: a service principal's name
159
+ # ("apigateway.amazonaws.com") or an ARN principal. The CDK takes
160
+ # principal objects; this tool has none (architecture section 21, the
161
+ # account-id-as-principal row).
162
+ def valid_principal(principal)
163
+ return principal if principal.is_a?(String) && !principal.empty?
164
+
165
+ raise UsageError, "#{path}: add_permission takes a service principal or an ARN String, got #{principal.inspect}"
166
+ end
167
+
168
+ # A literal ARN or a CloudFormation function, as the rule's own arn is.
169
+ def valid_source_arn(source_arn)
170
+ return nil if source_arn.nil?
171
+ return source_arn if source_arn.is_a?(String) && !source_arn.empty?
172
+ return source_arn if source_arn.is_a?(Hash) && !source_arn.empty?
173
+
174
+ raise UsageError, "#{path}: source_arn takes an ARN String or a CloudFormation function, got #{source_arn.inspect}"
175
+ end
176
+
177
+ def valid_source_account(source_account)
178
+ return nil if source_account.nil?
179
+ return source_account if source_account.is_a?(String) && !source_account.empty?
180
+ return source_account if source_account.is_a?(Hash) && !source_account.empty?
181
+
182
+ raise UsageError, "#{path}: source_account takes an account id String or a CloudFormation function, " \
183
+ "got #{source_account.inspect}"
184
+ end
185
+
127
186
  def valid_handler(handler)
128
187
  return handler if handler.is_a?(String) && !handler.empty?
129
188
 
@@ -0,0 +1,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+ require_relative "../fn"
5
+
6
+ module RubyCdk
7
+ module KMS
8
+ # A KMS key alias: the port of the CDK's Alias (aws-kms/lib/alias.ts), read
9
+ # at commit c070afb54b9e4dbddd52a85a21077fe970354985, Apache-2.0.
10
+ #
11
+ # key.add_alias("prod/session")
12
+ # RubyCdk::KMS::Alias.new(stack, "Alias", alias_name: "prod/session",
13
+ # target_key: "arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab")
14
+ #
15
+ # The name follows the CDK's rules (alias.ts:341-359): "alias/" is put in
16
+ # front when it is missing, something has to follow it, "alias/aws/" is
17
+ # reserved, and the name is 1 to 256 characters of letters, digits, ":",
18
+ # "/", "_" and "-". TargetKeyId is the key's ARN (alias.ts:384-387):
19
+ # target_key is a KMS::Key, a key ARN or an intrinsic. The alias is deleted
20
+ # with the stack, as in the CDK: AWS::KMS::Alias is not one of the types
21
+ # the CDK retains.
22
+ #
23
+ # Not here: Alias.fromAliasAttributes and Alias.fromAliasName, the two
24
+ # imports (D-022), and removalPolicy on the alias.
25
+ class Alias < Construct
26
+ REQUIRED_PREFIX = "alias/"
27
+
28
+ DISALLOWED_PREFIX = "#{REQUIRED_PREFIX}aws/"
29
+
30
+ # The CDK's /^[a-zA-Z0-9:/_-]{1,256}$/, with the strict anchor.
31
+ NAME_PATTERN = %r{\A[a-zA-Z0-9:/_-]{1,256}\z}
32
+
33
+ attr_reader :alias_name
34
+
35
+ def initialize(scope, id, alias_name:, target_key:)
36
+ super(scope, id)
37
+ @alias_name = self.class.name_of(alias_name, path)
38
+ @target_key = KMS.key_reference(target_key, "#{path}: target_key")
39
+
40
+ @resource = resource("Resource", "AWS::KMS::Alias",
41
+ AliasName: @alias_name,
42
+ TargetKeyId: KMS.key_arn(@target_key))
43
+ end
44
+
45
+ # The logical ID of the AWS::KMS::Alias under this construct.
46
+ def logical_id
47
+ @resource.logical_id
48
+ end
49
+
50
+ # The ARN of the alias (alias.ts:104-110): arn:<partition>:kms:<region>:
51
+ # <account>:<alias name>. One Fn::Sub over CloudFormation's pseudo
52
+ # parameters, so it works in a stack with no concrete env.
53
+ def alias_arn
54
+ Fn.sub("arn:${AWS::Partition}:kms:${AWS::Region}:${AWS::AccountId}:${AliasName}",
55
+ "AliasName" => @alias_name)
56
+ end
57
+
58
+ # The name as it is written (alias.ts:342-359): the prefix in front when
59
+ # missing, then the three refusals, in the CDK's order and with its
60
+ # words.
61
+ def self.name_of(name, where)
62
+ unless name.is_a?(String)
63
+ raise UsageError, "#{where}: the alias name must be a String, got #{name.inspect}"
64
+ end
65
+
66
+ name = "#{REQUIRED_PREFIX}#{name}" unless name.start_with?(REQUIRED_PREFIX)
67
+ if name == REQUIRED_PREFIX
68
+ raise UsageError, "#{where}: Alias must include a value after \"#{REQUIRED_PREFIX}\": #{name}"
69
+ end
70
+ if name.downcase.start_with?(DISALLOWED_PREFIX)
71
+ raise UsageError, "#{where}: Alias cannot start with #{DISALLOWED_PREFIX}: #{name}"
72
+ end
73
+ unless NAME_PATTERN.match?(name)
74
+ raise UsageError, "#{where}: Alias name must be between 1 and 256 characters in a-zA-Z0-9:/_-"
75
+ end
76
+
77
+ name
78
+ end
79
+
80
+ # The construct id of an alias a key adds after its first. The CDK's is
81
+ # "Alias" and the alias name (key.ts:172), which cannot be an id here: an
82
+ # id holds no "/" or ":". The name behind alias/ is spelled as a logical
83
+ # ID is spelled elsewhere in this tool, each word capitalized: alias/xoo
84
+ # is AliasXoo, and so is a bare xoo, the same alias.
85
+ def self.id_for(name)
86
+ "Alias#{name.delete_prefix(REQUIRED_PREFIX).split(/[^A-Za-z0-9]+/).map(&:capitalize).join}"
87
+ end
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,436 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+ require_relative "../fn"
5
+ require_relative "../lazy"
6
+ require_relative "grant"
7
+ require_relative "policy_statement"
8
+ require_relative "kms_alias"
9
+
10
+ module RubyCdk
11
+ module KMS
12
+ # What the constructs take for a key - S3::Bucket's encryption_key:,
13
+ # SQS::Queue's encryption_master_key:, SNS::Topic's master_key: and
14
+ # DynamoDB::Table's encryption_key: - checked here once: a Key of this app,
15
+ # the ARN of a key that exists (the CDK's Key.fromKeyArn, key.ts:606-621),
16
+ # or an intrinsic that resolves to one. Answers the key as it was given.
17
+ #
18
+ # An ARN is a reference and nothing else: it enters no tree, is looked up
19
+ # nowhere (D-022) and has no policy to write to, which is why the grants
20
+ # below go to the principal's own policy for it, as the CDK's do for an
21
+ # imported key (key.ts:616-619).
22
+ module_function
23
+
24
+ def key_reference(value, where)
25
+ return value if value.is_a?(Key)
26
+ return key_arn_string(value, where) if value.is_a?(String)
27
+ return value if value.is_a?(Hash)
28
+
29
+ Kernel.raise UsageError, "#{where} takes a RubyCdk::KMS::Key, a key ARN or an intrinsic, got #{value.inspect}"
30
+ end
31
+
32
+ # The ARN a key reference stands for.
33
+ def key_arn(key)
34
+ key.is_a?(Key) ? key.key_arn : key
35
+ end
36
+
37
+ # Grants the actions on the key to the principal, on the principal's own
38
+ # policy (Grant.add_to_principal): what a construct's grant_* does with the
39
+ # key it was given, the CDK's `key.grant(grantee, ...actions)`
40
+ # (key-grants.ts:43-82) on a key and a principal of one account.
41
+ def grant_on_key(key, principal, actions)
42
+ Constructs::Grant.add_to_principal(principal, actions, [ key_arn(key) ])
43
+ end
44
+
45
+ # The CDK's one check on the ARN of an imported key (key.ts:606-610):
46
+ # splitArn with a slash resource name (core/lib/arn.ts:235-308) has to
47
+ # find a resource name behind the slash, and the partition is required
48
+ # (arn.ts:433-435). The slash form alone is taken, the one the message
49
+ # names: KMS issues no other.
50
+ def key_arn_string(arn, where)
51
+ parts = arn.split(":", 6)
52
+ name = parts[5]&.split("/", 2)&.at(1)
53
+ unless arn.start_with?("arn:") && parts.length == 6 && !parts[1].empty? && name && !name.empty?
54
+ Kernel.raise UsageError, "#{where}: KMS key ARN must be in the format 'arn:<partition>:kms:<region>:<account>:key/<keyId>', " \
55
+ "got: '#{arn}'"
56
+ end
57
+
58
+ arn
59
+ end
60
+ private_class_method :key_arn_string
61
+
62
+ # A KMS key: the port of the CDK's Key (aws-kms/lib/key.ts), read at
63
+ # commit c070afb54b9e4dbddd52a85a21077fe970354985, Apache-2.0.
64
+ #
65
+ # RubyCdk::KMS::Key.new(stack, "Key", description: "Session secrets", enable_key_rotation: true)
66
+ # RubyCdk::KMS::Key.new(stack, "Key", alias_name: "prod/session")
67
+ # key.grant_encrypt_decrypt(role)
68
+ #
69
+ # The key policy is the CDK's default: one statement giving the account's
70
+ # root kms:* on everything (addDefaultAdminPolicy, key.ts:906-912), the
71
+ # statement the KMS API and console start a key with, through which the
72
+ # account's IAM policies delegate access to the key. That is what the CDK
73
+ # writes with its defaultKeyPolicies flag, the default of CDK v2
74
+ # (cx-api/lib/features.ts:282-302); the flag and the deprecated
75
+ # trustAccountIdentities prop behind it are not options here. policy:
76
+ # replaces the default with the statements given; add_to_resource_policy
77
+ # appends one later. The policy is resolved at synthesis, and a statement
78
+ # without an action, a principal or a resource fails it with the CDK's
79
+ # words (aws-iam/lib/policy-statement.ts:547-571).
80
+ #
81
+ # The root principal is written over CloudFormation's pseudo parameters,
82
+ # Fn::Join of AWS::Partition and AWS::AccountId, as the CDK writes it in a
83
+ # stack without a concrete env (its "default key" case); the CDK writes
84
+ # the literal account when the stack's env names it. CloudFormation
85
+ # resolves the same ARN in the stack's account.
86
+ #
87
+ # key_spec and key_usage take the CDK's KeySpec and KeyUsage names as a
88
+ # Symbol (key_spec: :rsa_4096, key_usage: :sign_verify) or as the name
89
+ # itself; the defaults are SYMMETRIC_DEFAULT and ENCRYPT_DECRYPT, and the
90
+ # CDK's table of the specs each usage refuses is kept (key.ts:755-809) -
91
+ # with the CDK's own bounds: rotation periods are checked against 90 and
92
+ # 2560 days in a message that says 2650 (key.ts:825-826).
93
+ #
94
+ # alias_name is the CDK's alias prop (key.ts:882-884): the first alias of
95
+ # the key, an AWS::KMS::Alias under it; add_alias adds more. admins are
96
+ # roles granted the key's admin actions (key.ts:880, grantAdmin) - IAM::Role
97
+ # alone, since a grant here goes to an identity's own policy and never to
98
+ # the key's.
99
+ #
100
+ # The grants are the CDK's (key-grants.ts and private/perms.ts), each one
101
+ # statement of the actions on the key's ARN, on the principal's own policy
102
+ # through Grant.add_to_principal: grant_decrypt, grant_encrypt,
103
+ # grant_encrypt_decrypt, grant_sign, grant_verify, grant_sign_verify,
104
+ # grant_generate_mac, grant_verify_mac, grant_admin, and grant for any
105
+ # actions. The CDK's grant writes the principal's policy when the principal
106
+ # is of the key's account and the key's own policy otherwise
107
+ # (Grant.addToPrincipalOrResource, key-grants.ts:72-73); here it is always
108
+ # the principal's (architecture section 21, the grant mechanics row).
109
+ #
110
+ # AWS::KMS::Key is one of the retained types (architecture section 7):
111
+ # synthesis gives it RetainExceptOnCreate and Retain, as it gives every
112
+ # AWS::KMS::Key, and the construct writes no deletion policy of its own.
113
+ #
114
+ # Not here: Key.fromLookup (D-022), Key.fromCfnKey, removalPolicy (the L1
115
+ # resource's deletion_policy: is the way to write one), the grant methods
116
+ # of an Alias over the key it names, and the resource-policy side of a
117
+ # grant to a principal of another account or a service.
118
+ class Key < Construct
119
+ # The CDK's KeySpec names (key.ts:288-410), as CloudFormation takes them.
120
+ KEY_SPECS = %w[
121
+ SYMMETRIC_DEFAULT
122
+ RSA_2048
123
+ RSA_3072
124
+ RSA_4096
125
+ ECC_NIST_P256
126
+ ECC_NIST_P384
127
+ ECC_NIST_P521
128
+ ECC_SECG_P256K1
129
+ HMAC_224
130
+ HMAC_256
131
+ HMAC_384
132
+ HMAC_512
133
+ SM2
134
+ ML_DSA_44
135
+ ML_DSA_65
136
+ ML_DSA_87
137
+ ECC_NIST_EDWARDS25519
138
+ ].freeze
139
+
140
+ # The CDK's KeyUsage names (key.ts:415-435).
141
+ KEY_USAGES = %w[ ENCRYPT_DECRYPT SIGN_VERIFY GENERATE_VERIFY_MAC KEY_AGREEMENT ].freeze
142
+
143
+ DEFAULT_KEY_SPEC = "SYMMETRIC_DEFAULT"
144
+ DEFAULT_KEY_USAGE = "ENCRYPT_DECRYPT"
145
+
146
+ # The specs each usage refuses (key.ts:755-804).
147
+ DENIED_SPECS = {
148
+ "ENCRYPT_DECRYPT" => %w[
149
+ ECC_NIST_P256 ECC_NIST_P384 ECC_NIST_P521 ECC_SECG_P256K1
150
+ HMAC_224 HMAC_256 HMAC_384 HMAC_512 ML_DSA_44 ML_DSA_65 ML_DSA_87
151
+ ],
152
+ "SIGN_VERIFY" => %w[ SYMMETRIC_DEFAULT HMAC_224 HMAC_256 HMAC_384 HMAC_512 ],
153
+ "GENERATE_VERIFY_MAC" => %w[
154
+ RSA_2048 RSA_3072 RSA_4096 ECC_NIST_P256 ECC_NIST_P384 ECC_NIST_P521 ECC_SECG_P256K1
155
+ SYMMETRIC_DEFAULT SM2 ML_DSA_44 ML_DSA_65 ML_DSA_87
156
+ ],
157
+ "KEY_AGREEMENT" => %w[
158
+ SYMMETRIC_DEFAULT RSA_2048 RSA_3072 RSA_4096 ECC_SECG_P256K1
159
+ HMAC_224 HMAC_256 HMAC_384 HMAC_512 ML_DSA_44 ML_DSA_65 ML_DSA_87
160
+ ]
161
+ }.freeze
162
+
163
+ # The CDK's action sets (aws-kms/lib/private/perms.ts).
164
+ ADMIN_ACTIONS = %w[
165
+ kms:Create* kms:Describe* kms:Enable* kms:List* kms:Put* kms:Update* kms:Revoke* kms:Disable*
166
+ kms:Get* kms:Delete* kms:TagResource kms:UntagResource kms:ScheduleKeyDeletion kms:CancelKeyDeletion
167
+ ].freeze
168
+
169
+ ENCRYPT_ACTIONS = %w[ kms:Encrypt kms:ReEncrypt* kms:GenerateDataKey* ].freeze
170
+ DECRYPT_ACTIONS = %w[ kms:Decrypt ].freeze
171
+ SIGN_ACTIONS = %w[ kms:Sign ].freeze
172
+ VERIFY_ACTIONS = %w[ kms:Verify ].freeze
173
+ GENERATE_MAC_ACTIONS = %w[ kms:GenerateMac ].freeze
174
+ VERIFY_MAC_ACTIONS = %w[ kms:VerifyMac ].freeze
175
+
176
+ # The CDK's bounds (key.ts:825-826, 859).
177
+ MIN_ROTATION_PERIOD_DAYS = 90
178
+ MAX_ROTATION_PERIOD_DAYS = 2560
179
+ MIN_PENDING_WINDOW_DAYS = 7
180
+ MAX_PENDING_WINDOW_DAYS = 30
181
+
182
+ POLICY_VERSION = "2012-10-17"
183
+
184
+ def initialize(scope, id, description: nil, alias_name: nil, enable_key_rotation: nil, rotation_period: nil,
185
+ enabled: nil, key_spec: nil, key_usage: nil, multi_region: nil, policy: nil, admins: [], pending_window: nil)
186
+ super(scope, id)
187
+ @description = text(description, "description")
188
+ @key_spec = enum_name(key_spec, KEY_SPECS, "key_spec")
189
+ @key_usage = enum_name(key_usage, KEY_USAGES, "key_usage")
190
+ spec = @key_spec || DEFAULT_KEY_SPEC
191
+ usage = @key_usage || DEFAULT_KEY_USAGE
192
+ if DENIED_SPECS.fetch(usage).include?(spec)
193
+ raise UsageError, "#{path}: key spec '#{spec}' is not valid with usage '#{usage}'"
194
+ end
195
+ if spec.start_with?("HMAC") && enable_key_rotation
196
+ raise UsageError, "#{path}: key rotation cannot be enabled on HMAC keys"
197
+ end
198
+ if spec != DEFAULT_KEY_SPEC && enable_key_rotation
199
+ raise UsageError, "#{path}: key rotation cannot be enabled on asymmetric keys"
200
+ end
201
+
202
+ @enable_key_rotation = flag(enable_key_rotation, "enable_key_rotation")
203
+ @rotation_period = days(rotation_period, "rotation_period")
204
+ if @rotation_period
205
+ if enable_key_rotation == false
206
+ raise UsageError, "#{path}: 'rotation_period' cannot be specified when 'enable_key_rotation' is disabled"
207
+ end
208
+ if @rotation_period < MIN_ROTATION_PERIOD_DAYS || @rotation_period > MAX_ROTATION_PERIOD_DAYS
209
+ raise UsageError, "#{path}: 'rotation_period' value must between 90 and 2650 days. Received: #{@rotation_period}"
210
+ end
211
+ @enable_key_rotation = true if enable_key_rotation.nil?
212
+ end
213
+
214
+ @enabled = flag(enabled, "enabled")
215
+ @multi_region = flag(multi_region, "multi_region")
216
+ @pending_window = days(pending_window, "pending_window")
217
+ if @pending_window &&
218
+ (@pending_window < MIN_PENDING_WINDOW_DAYS || @pending_window > MAX_PENDING_WINDOW_DAYS)
219
+ raise UsageError, "#{path}: 'pending_window' value must between 7 and 30 days. Received: #{@pending_window}"
220
+ end
221
+
222
+ @statements = policy.nil? ? [ default_admin_statement ] : policy_statements(policy)
223
+ @aliases = []
224
+
225
+ @resource = resource("Resource", "AWS::KMS::Key",
226
+ Description: @description,
227
+ EnableKeyRotation: @enable_key_rotation,
228
+ Enabled: @enabled,
229
+ KeyPolicy: Lazy.new { rendered_policy },
230
+ KeySpec: @key_spec,
231
+ KeyUsage: @key_usage,
232
+ MultiRegion: @multi_region,
233
+ PendingWindowInDays: @pending_window,
234
+ RotationPeriodInDays: @rotation_period)
235
+
236
+ Array(admins).each { |admin| grant_admin(identity(admin)) }
237
+ add_alias(alias_name) if alias_name
238
+ end
239
+
240
+ # The logical ID of the AWS::KMS::Key under this construct.
241
+ def logical_id
242
+ @resource.logical_id
243
+ end
244
+
245
+ # The key's ARN: what a KMSMasterKeyId takes.
246
+ def key_arn
247
+ Fn.get_att(@resource, "Arn")
248
+ end
249
+
250
+ alias arn key_arn
251
+
252
+ # The key's ID: the Ref of the resource.
253
+ def key_id
254
+ Fn.ref(@resource)
255
+ end
256
+
257
+ # Adds an alias to the key (key.ts:171-178): an AWS::KMS::Alias named by
258
+ # alias_name, targeting the key's ARN. The first sits under the id Alias,
259
+ # as in the CDK; each later one under Alias and its name spelled as an
260
+ # id (Alias.id_for), since the CDK's "Alias" plus the alias name is not
261
+ # an id here. Two names that spell the same id are refused, as two
262
+ # constructs of one id are. Answers the KMS::Alias.
263
+ def add_alias(alias_name)
264
+ name = Alias.name_of(alias_name, path)
265
+ id = @aliases.empty? ? "Alias" : Alias.id_for(name)
266
+ created = Alias.new(self, id, alias_name: name, target_key: self)
267
+ @aliases << created
268
+ created
269
+ end
270
+
271
+ # Adds a statement to the key's policy (key.ts:187-197): an
272
+ # IAM::PolicyStatement, with its principal, or a Hash in CloudFormation's
273
+ # statement shape. The default statement stays; policy: is what replaces
274
+ # it.
275
+ def add_to_resource_policy(statement)
276
+ @statements << as_statement(statement)
277
+ self
278
+ end
279
+
280
+ # Grants the actions on this key to the principal: the CDK's grant
281
+ # (key.ts:208-210). An IAM::Role carries the statement on its own policy;
282
+ # a principal named by ARN gets the Grant back unapplied.
283
+ def grant(principal, *actions)
284
+ Constructs::Grant.add_to_principal(principal, actions, [ key_arn ])
285
+ end
286
+
287
+ # Grants the actions that manage the key, not use it (key.ts:896-898).
288
+ def grant_admin(principal)
289
+ grant(principal, *ADMIN_ACTIONS)
290
+ end
291
+
292
+ # Grants kms:Decrypt (key.ts:217-219).
293
+ def grant_decrypt(principal)
294
+ grant(principal, *DECRYPT_ACTIONS)
295
+ end
296
+
297
+ # Grants the encrypt actions: Encrypt, ReEncrypt* and GenerateDataKey*
298
+ # (key.ts:226-228).
299
+ def grant_encrypt(principal)
300
+ grant(principal, *ENCRYPT_ACTIONS)
301
+ end
302
+
303
+ # Grants the decrypt action and then the encrypt actions
304
+ # (key-grants.ts:114-116).
305
+ def grant_encrypt_decrypt(principal)
306
+ grant(principal, *DECRYPT_ACTIONS, *ENCRYPT_ACTIONS)
307
+ end
308
+
309
+ # Grants kms:Sign (key.ts:244-246).
310
+ def grant_sign(principal)
311
+ grant(principal, *SIGN_ACTIONS)
312
+ end
313
+
314
+ # Grants kms:Verify (key.ts:253-255).
315
+ def grant_verify(principal)
316
+ grant(principal, *VERIFY_ACTIONS)
317
+ end
318
+
319
+ # Grants Sign and Verify (key-grants.ts:138-140).
320
+ def grant_sign_verify(principal)
321
+ grant(principal, *SIGN_ACTIONS, *VERIFY_ACTIONS)
322
+ end
323
+
324
+ # Grants kms:GenerateMac (key.ts:271-273).
325
+ def grant_generate_mac(principal)
326
+ grant(principal, *GENERATE_MAC_ACTIONS)
327
+ end
328
+
329
+ # Grants kms:VerifyMac (key.ts:280-282).
330
+ def grant_verify_mac(principal)
331
+ grant(principal, *VERIFY_MAC_ACTIONS)
332
+ end
333
+
334
+ private
335
+
336
+ # The default statement (addDefaultAdminPolicy, key.ts:906-912): kms:* on
337
+ # everything to AccountRootPrincipal, the account's root ARN
338
+ # (aws-iam/lib/principals.ts:812-820).
339
+ def default_admin_statement
340
+ IAM::PolicyStatement.new(
341
+ actions: [ "kms:*" ],
342
+ resources: [ "*" ],
343
+ principals: { "AWS" => Fn.join("", [ "arn:", Fn.ref("AWS::Partition"), ":iam::", Fn.ref("AWS::AccountId"), ":root" ]) })
344
+ end
345
+
346
+ # policy: is one statement or a list of them; nil is not a policy but the
347
+ # default, and an empty list is a policy with no statement.
348
+ def policy_statements(policy)
349
+ list = policy.is_a?(Array) ? policy : [ policy ]
350
+ list.map { |statement| as_statement(statement) }
351
+ end
352
+
353
+ def as_statement(statement)
354
+ return statement if statement.is_a?(IAM::PolicyStatement) || statement.is_a?(Hash)
355
+
356
+ raise UsageError, "#{path}: a key policy statement is an IAM::PolicyStatement or a Hash in CloudFormation's shape, " \
357
+ "got #{statement.inspect}"
358
+ end
359
+
360
+ # The policy as the template holds it (aws-iam/lib/policy-document.ts:310-315).
361
+ def rendered_policy
362
+ statements = @statements.map { |statement| statement_rendered(statement) }
363
+ statements.each { |statement| validate_resource_statement(statement) }
364
+ { "Statement" => statements, "Version" => POLICY_VERSION }
365
+ end
366
+
367
+ def statement_rendered(statement)
368
+ return statement.to_statement if statement.is_a?(IAM::PolicyStatement)
369
+
370
+ statement.to_h { |key, value| [ key.to_s, value ] }
371
+ end
372
+
373
+ # The CDK's validateForResourcePolicy (aws-iam/lib/policy-statement.ts:547-571),
374
+ # which it reports at synthesis (key.ts:150). Here the Lazy raises, and
375
+ # the resolver makes it an issue at the policy's place in the template.
376
+ def validate_resource_statement(statement)
377
+ if none?(statement, "Action", "NotAction")
378
+ raise Error, "#{path}: A PolicyStatement must specify at least one 'action' or 'notAction'."
379
+ end
380
+ if none?(statement, "Principal", "NotPrincipal")
381
+ raise Error, "#{path}: A PolicyStatement used in a resource-based policy must specify at least one IAM principal."
382
+ end
383
+ return unless none?(statement, "Resource", "NotResource")
384
+
385
+ raise Error, "#{path}: A PolicyStatement used in a resource-based policy must specify at least one resource."
386
+ end
387
+
388
+ def none?(statement, *keys)
389
+ keys.all? do |key|
390
+ value = statement[key]
391
+ value.nil? || (value.respond_to?(:empty?) && value.empty?)
392
+ end
393
+ end
394
+
395
+ def identity(admin)
396
+ return admin if admin.is_a?(IAM::Role)
397
+
398
+ raise UsageError, "#{path}: admins takes IAM::Role identities, got #{admin.inspect}. A principal that cannot carry " \
399
+ "a statement of its own would have to be written into the key's policy, which no grant does here: give it " \
400
+ "through policy: instead"
401
+ end
402
+
403
+ def text(value, what)
404
+ return nil if value.nil?
405
+ return value if value.is_a?(String)
406
+
407
+ raise UsageError, "#{path}: #{what} must be a String, got #{value.inspect}"
408
+ end
409
+
410
+ def flag(value, what)
411
+ return nil if value.nil?
412
+ return value if value == true || value == false
413
+
414
+ raise UsageError, "#{path}: #{what} takes true or false, got #{value.inspect}"
415
+ end
416
+
417
+ def days(value, what)
418
+ return nil if value.nil?
419
+ return value if value.is_a?(Integer) && value.positive?
420
+
421
+ raise UsageError, "#{path}: #{what} takes a whole number of days, got #{value.inspect}"
422
+ end
423
+
424
+ # A Symbol is read as the name whatever its case (:rsa_4096); a String
425
+ # is the name itself. nil is not given.
426
+ def enum_name(value, names, what)
427
+ return nil if value.nil?
428
+
429
+ name = value.is_a?(Symbol) ? value.name.upcase : value
430
+ return name if name.is_a?(String) && names.include?(name)
431
+
432
+ raise UsageError, "#{path}: #{what} takes one of #{names.join(", ")} (a Symbol or the name), got #{value.inspect}"
433
+ end
434
+ end
435
+ end
436
+ end