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
@@ -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 SQS
@@ -11,6 +12,7 @@ module RubyCdk
11
12
  #
12
13
  # RubyCdk::SQS::Queue.new(stack, "Jobs",
13
14
  # queue_name: "jobs", visibility_timeout: 60, retention: 3_600)
15
+ # RubyCdk::SQS::Queue.new(stack, "Jobs", encryption: :kms, encryption_master_key: key)
14
16
  #
15
17
  # fifo: true marks the queue FIFO - the queue name then has to end in
16
18
  # .fifo, as SQS requires, and the CDK's own naming rule appends the suffix
@@ -18,21 +20,38 @@ module RubyCdk
18
20
  # section 7): nothing is written where the CDK writes Delete on both
19
21
  # policies, because the queue is deleted all the same.
20
22
  #
21
- # The grants are the CDK's (aws-sqs/lib/queue-base.ts and its tests, at the
23
+ # Encryption is the CDK's _determineEncryptionProps (queue.ts:458-528),
24
+ # its QueueEncryption as Symbols:
25
+ #
26
+ # - nothing given: no property is written, as in the CDK, and AWS
27
+ # encrypts a new queue at rest with an SQS-managed key.
28
+ # - :unencrypted: SqsManagedSseEnabled false.
29
+ # - :kms_managed: KmsMasterKeyId alias/aws/sqs, the AWS-managed key.
30
+ # - :kms: KmsMasterKeyId a customer-managed key's ARN - the one given as
31
+ # encryption_master_key (a RubyCdk::KMS::Key, a key ARN or an
32
+ # intrinsic), or else a key created under the queue, id Key, described
33
+ # "Created by <the queue's path>".
34
+ # - :sqs_managed: SqsManagedSseEnabled true.
35
+ #
36
+ # data_key_reuse is the seconds of KmsDataKeyReusePeriodSeconds beside
37
+ # either KMS mode. A master key with :sqs_managed is refused, as in the
38
+ # CDK. A master key with no encryption: implies :kms, as in the CDK. A
39
+ # master key with another mode given the CDK switches to KMS and annotates
40
+ # a warning (queue.ts:469-478); constructs write no annotations here, so
41
+ # that is refused with the CDK's advice in the message. encryption_type is
42
+ # the mode in the end.
43
+ #
44
+ # The grants are the CDK's (aws-sqs/grants.json and queue-base.ts, at the
22
45
  # pinned commit): consume is ReceiveMessage, ChangeMessageVisibility,
23
46
  # GetQueueUrl, DeleteMessage and GetQueueAttributes; send is SendMessage,
24
47
  # GetQueueAttributes and GetQueueUrl; purge is PurgeQueue,
25
48
  # GetQueueAttributes and GetQueueUrl; and grant takes any actions given.
26
49
  # All on the queue's ARN, to the principal's own policy - the CDK's
27
50
  # QueuePolicy exists for principals that cannot carry a statement, which is
28
- # not a case here.
29
- #
30
- # Encryption: this tool takes no option and writes no property, exactly as
31
- # the CDK at the pinned commit does when props.encryption is unset
32
- # (_determineEncryptionProps, queue.ts:459-468 writes {}): AWS encrypts a
33
- # new queue at rest with an SQS-managed key by default, so the template
34
- # says nothing. A customer-managed key needs KmsMasterKeyId, which this
35
- # tool does not yet take; architecture section 21 records the row.
51
+ # not a case here. Under a customer-managed key, consume also grants
52
+ # kms:Decrypt on the key and send kms:Decrypt, kms:Encrypt, kms:ReEncrypt*
53
+ # and kms:GenerateDataKey* (grants.json, keyActions), a second statement on
54
+ # the same policy; purge grants nothing on the key.
36
55
  class Queue < Construct
37
56
  # The CDK's consume actions, in its order (queue-base.ts, its grant test).
38
57
  CONSUME_ACTIONS = [
@@ -46,9 +65,21 @@ module RubyCdk
46
65
  # The CDK's purge actions, in its order.
47
66
  PURGE_ACTIONS = [ "sqs:PurgeQueue", "sqs:GetQueueAttributes", "sqs:GetQueueUrl" ].freeze
48
67
 
49
- attr_reader :fifo
68
+ # The key actions of the two grants (aws-sqs/grants.json,
69
+ # consumeMessages.keyActions and sendMessages.keyActions).
70
+ CONSUME_KEY_ACTIONS = [ "kms:Decrypt" ].freeze
71
+ SEND_KEY_ACTIONS = [ "kms:Decrypt", "kms:Encrypt", "kms:ReEncrypt*", "kms:GenerateDataKey*" ].freeze
72
+
73
+ # The CDK's managed key, by its alias (queue.ts:497).
74
+ MANAGED_KEY_ALIAS = "alias/aws/sqs"
50
75
 
51
- def initialize(scope, id, queue_name: nil, fifo: false, visibility_timeout: nil, retention: nil)
76
+ ENCRYPTIONS = %i[unencrypted kms_managed kms sqs_managed].freeze
77
+ private_constant :ENCRYPTIONS
78
+
79
+ attr_reader :fifo, :encryption_type, :encryption_master_key
80
+
81
+ def initialize(scope, id, queue_name: nil, fifo: false, visibility_timeout: nil, retention: nil,
82
+ encryption: nil, encryption_master_key: nil, data_key_reuse: nil)
52
83
  super(scope, id)
53
84
  @fifo = fifo ? true : false
54
85
  @queue_name = queue_name.nil? || queue_name.is_a?(String) && !queue_name.empty? ? queue_name :
@@ -57,9 +88,14 @@ module RubyCdk
57
88
  @queue_name = "#{@queue_name}.fifo"
58
89
  end
59
90
 
91
+ master_key = encryption_master_key && KMS.key_reference(encryption_master_key, "#{path}: encryption_master_key")
92
+ @encryption_type, @encryption_master_key, encryption_props =
93
+ encryption_settings(encryption, master_key, valid_seconds(data_key_reuse, "data_key_reuse"))
94
+
60
95
  @resource = resource("Resource", "AWS::SQS::Queue",
61
96
  QueueName: @queue_name,
62
97
  FifoQueue: @fifo || nil,
98
+ **encryption_props,
63
99
  VisibilityTimeout: valid_seconds(visibility_timeout, "visibility_timeout"),
64
100
  MessageRetentionPeriod: valid_seconds(retention, "retention"))
65
101
  end
@@ -81,14 +117,20 @@ module RubyCdk
81
117
  end
82
118
 
83
119
  # Grants the consume actions to the principal (queue-base.ts,
84
- # grantConsumeMessages).
120
+ # grantConsumeMessages), and the key's decrypt under a customer-managed
121
+ # key.
85
122
  def grant_consume_messages(principal)
86
- Constructs::Grant.add_to_principal(principal, CONSUME_ACTIONS, [ arn ])
123
+ grant = Constructs::Grant.add_to_principal(principal, CONSUME_ACTIONS, [ arn ])
124
+ KMS.grant_on_key(@encryption_master_key, principal, CONSUME_KEY_ACTIONS) if @encryption_master_key
125
+ grant
87
126
  end
88
127
 
89
- # Grants the send actions (queue-base.ts, grantSendMessages).
128
+ # Grants the send actions (queue-base.ts, grantSendMessages), and the
129
+ # key's actions under a customer-managed key.
90
130
  def grant_send_messages(principal)
91
- Constructs::Grant.add_to_principal(principal, SEND_ACTIONS, [ arn ])
131
+ grant = Constructs::Grant.add_to_principal(principal, SEND_ACTIONS, [ arn ])
132
+ KMS.grant_on_key(@encryption_master_key, principal, SEND_KEY_ACTIONS) if @encryption_master_key
133
+ grant
92
134
  end
93
135
 
94
136
  # Grants the purge actions (queue-base.ts, grantPurge).
@@ -113,6 +155,43 @@ module RubyCdk
113
155
 
114
156
  raise UsageError, "#{path}: #{what} must be a positive number of seconds or an intrinsic, got #{value.inspect}"
115
157
  end
158
+
159
+ def valid_encryption(value)
160
+ return nil if value.nil?
161
+ return value if ENCRYPTIONS.include?(value)
162
+
163
+ raise UsageError, "#{path}: encryption takes :unencrypted, :kms_managed, :kms, :sqs_managed or nil, got #{value.inspect}"
164
+ end
165
+
166
+ # The port of _determineEncryptionProps (queue.ts:458-528). Answers
167
+ # [the mode, the master key, the properties to write].
168
+ def encryption_settings(encryption, master_key, data_key_reuse)
169
+ encryption = valid_encryption(encryption)
170
+ if encryption == :sqs_managed && master_key
171
+ raise UsageError, "#{path}: 'encryption_master_key' is not supported if encryption type 'SQS_MANAGED' is used"
172
+ end
173
+ if encryption != :kms && master_key
174
+ if encryption
175
+ raise UsageError, "#{path}: encryption_master_key is given with encryption: #{encryption.inspect}. " \
176
+ "When encryptionMasterKey is provided, always set `encryption: QueueEncryption.KMS` (encryption: :kms here), " \
177
+ "or leave encryption: out and KMS is implied"
178
+ end
179
+ encryption = :kms
180
+ end
181
+ return [ nil, nil, {} ] unless encryption
182
+
183
+ case encryption
184
+ when :unencrypted
185
+ [ encryption, nil, { "SqsManagedSseEnabled" => false } ]
186
+ when :kms_managed
187
+ [ encryption, nil, { "KmsMasterKeyId" => MANAGED_KEY_ALIAS, "KmsDataKeyReusePeriodSeconds" => data_key_reuse } ]
188
+ when :kms
189
+ master_key ||= KMS::Key.new(self, "Key", description: "Created by #{path}")
190
+ [ encryption, master_key, { "KmsMasterKeyId" => KMS.key_arn(master_key), "KmsDataKeyReusePeriodSeconds" => data_key_reuse } ]
191
+ when :sqs_managed
192
+ [ encryption, nil, { "SqsManagedSseEnabled" => true } ]
193
+ end
194
+ end
116
195
  end
117
196
  end
118
197
  end
@@ -0,0 +1,234 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "json"
5
+ require_relative "../errors"
6
+ require_relative "../fn"
7
+ require_relative "grant"
8
+
9
+ module RubyCdk
10
+ module ApiGateway
11
+ # A REST API with a Lambda proxy: the port of the CDK's LambdaRestApi over
12
+ # the RestApi it extends (aws-apigateway/lib/lambda-api.ts,
13
+ # integrations/lambda.ts and restapi.ts), read at commit
14
+ # c070afb54b9e4dbddd52a85a21077fe970354985, Apache-2.0.
15
+ #
16
+ # api = RubyCdk::ApiGateway::RestApi.new(stack, "Api",
17
+ # handler: function, rest_api_name: "notes-api")
18
+ #
19
+ # One construct builds the six resources the CDK's own minimal template
20
+ # shows (its restapi.test.ts, "minimal setup") plus the permission the
21
+ # invocation needs: the AWS::ApiGateway::RestApi
22
+ # named after the construct's id when rest_api_name is left out
23
+ # (restapi.ts:436), the {proxy+} resource under the root
24
+ # (resource.ts:199-201), the ANY method on the proxy and on the root - a
25
+ # proxy under the root puts its method on both (resource.ts:630-640) - the
26
+ # AWS::ApiGateway::Deployment (restapi.ts:737-752, "Automatically created
27
+ # by the RestApi construct") and the prod AWS::ApiGateway::Stage, the
28
+ # Endpoint output (restapi.ts:753, urlForPath), and the
29
+ # AWS::Lambda::Permission on the handler.
30
+ #
31
+ # The integration is the CDK's Lambda proxy: AWS_PROXY, POST, the
32
+ # invoke URI of the function (integrations/lambda.ts:47-59). Authorization
33
+ # is NONE, the CDK's default (method.ts:255), and authorization: takes the
34
+ # other three values the CDK's AuthorizationType has. Note the nag rule
35
+ # RC-APIGW-001: a method with AuthorizationType NONE fails it when the
36
+ # template is synthesized into cdk.out; pass authorization: :aws_iam and
37
+ # grant invoke to the caller's role to clear it.
38
+ #
39
+ # Where this tool differs from the CDK (architecture section 7 wins; the
40
+ # rows are listed in section 21):
41
+ #
42
+ # - One Lambda::Permission, on the function, for the whole API. The CDK's
43
+ # LambdaIntegration.bind gives apigateway.amazonaws.com permission to
44
+ # invoke the function, per method and scoped to the method's ARN, plus
45
+ # a second one for the console's test invoke (integrations/lambda.ts:
46
+ # 80-110); here the construct writes one AWS::Lambda::Permission,
47
+ # SourceArn one Fn::Sub over the execution ARN of the API with the API's
48
+ # Ref and stage, method and path all "*" - the CDK's arnForExecuteApi
49
+ # default (restapi.ts:504) as one Fn::Sub over the same five parts, as
50
+ # the SSM parameter ARN row writes it. The id names the API, so a
51
+ # function that backs two APIs gets two permissions (D-029).
52
+ # - No CloudWatch role and no AWS::ApiGateway::Account
53
+ # (restapi.ts:689-714): the account-wide effect of a role per API is
54
+ # not a safe default to write silently; logs go to the function's own
55
+ # role here.
56
+ # - The Deployment's logical id carries a short hash of the API's
57
+ # method set, as the CDK's one hashed logical id does
58
+ # (deployment.ts:63-77, 184-202): without it, a changed API would
59
+ # never reach a new deployment and the stage would keep serving the
60
+ # old one. D-004's rule - ids the user writes, never a hash - keeps
61
+ # every other id; this hash is over the method set, not over construct
62
+ # paths, so moving code replaces nothing and changing the API
63
+ # replaces only the deployment, which is the CDK's own semantics.
64
+ class RestApi < Construct
65
+ # The CDK's AuthorizationType values (method.ts, AuthorizationType).
66
+ AUTHORIZATION_TYPES = %w[NONE AWS_IAM COGNITO_USER_POOLS CUSTOM].freeze
67
+
68
+ # The CDK's stage name default (restapi.ts:744).
69
+ DEFAULT_STAGE_NAME = "prod"
70
+
71
+ # The CDK's deployment description (restapi.ts:740).
72
+ DEPLOYMENT_DESCRIPTION = "Automatically created by the RestApi construct"
73
+
74
+ # The invoke path of the Lambda proxy integration
75
+ # (integrations/lambda.ts:53-58).
76
+ INVOKE_PATH = "arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/" \
77
+ "2015-03-31/functions/${FunctionArn}/invocations"
78
+
79
+ # The SourceArn of the permission: the execution ARN of the API, every
80
+ # stage, method and path - the CDK's arnForExecuteApi default
81
+ # (restapi.ts:504), which the CDK renders an Fn::Join over (its
82
+ # integrations/lambda.test.ts, "scopePermissionToMethod set to false
83
+ # creates API-scoped permission"), as one Fn::Sub here.
84
+ EXECUTION_ARN = "arn:${AWS::Partition}:execute-api:${AWS::Region}:${AWS::AccountId}:${__ApiId}/*/*/*"
85
+
86
+ attr_reader :rest_api_name, :stage_name, :authorization
87
+
88
+ def initialize(scope, id, handler:, rest_api_name: nil, description: nil,
89
+ stage_name: DEFAULT_STAGE_NAME, authorization: "NONE")
90
+ super(scope, id)
91
+ @handler = valid_handler(handler)
92
+ @rest_api_name = rest_api_name.nil? ? id : valid_name(rest_api_name)
93
+ @stage_name = valid_stage_name(stage_name)
94
+ @authorization = valid_authorization(authorization)
95
+
96
+ api_properties = { "Name" => @rest_api_name, "Description" => description }
97
+ @api_resource = resource("Resource", "AWS::ApiGateway::RestApi", properties: api_properties)
98
+
99
+ @proxy_resource = resource("Proxy", "AWS::ApiGateway::Resource",
100
+ ParentId: Fn.get_att(@api_resource, "RootResourceId"),
101
+ PathPart: "{proxy+}",
102
+ RestApiId: Fn.ref(@api_resource))
103
+
104
+ method_properties = [
105
+ method_properties(Fn.get_att(@api_resource, "RootResourceId")),
106
+ method_properties(Fn.ref(@proxy_resource))
107
+ ]
108
+ @method_resources = method_properties.each_with_index.map do |properties, index|
109
+ resource(index.zero? ? "RootMethod" : "ProxyMethod", "AWS::ApiGateway::Method", properties: properties)
110
+ end
111
+
112
+ # The permission the invocation needs (integrations/lambda.ts:80-110):
113
+ # API Gateway calls the function as the service principal, which has no
114
+ # policy of its own, so the statement lands on the function's resource
115
+ # policy. The id names the API, so a function that backs two APIs gets
116
+ # two permissions (D-029). Proven necessary by the sandbox run of
117
+ # 2026-11-27: without it the endpoint answers 500.
118
+ @handler.add_permission("ApiPermission#{logical_id}", principal: "apigateway.amazonaws.com",
119
+ source_arn: Fn.sub(EXECUTION_ARN, "__ApiId" => Fn.ref(@api_resource)))
120
+
121
+ # The Deployment is the CDK's one hashed logical id: a short hash of
122
+ # the API's method set follows the ids in front of it, so a changed
123
+ # API gets a new deployment (deployment.ts:63-77, 184-202).
124
+ @deployment_resource = resource("Deployment#{hash_of(api_properties, method_properties)}",
125
+ "AWS::ApiGateway::Deployment",
126
+ RestApiId: Fn.ref(@api_resource),
127
+ Description: DEPLOYMENT_DESCRIPTION,
128
+ depends_on: @method_resources)
129
+
130
+ @stage_resource = resource("Stage", "AWS::ApiGateway::Stage",
131
+ StageName: @stage_name,
132
+ RestApiId: Fn.ref(@api_resource),
133
+ DeploymentId: Fn.ref(@deployment_resource))
134
+
135
+ # The Endpoint output, named after the API (restapi.ts:753): the id's
136
+ # letters and digits, so that a hyphenated id stays a legal output
137
+ # name. Two APIs whose stripped ids agree collide loudly here, at the
138
+ # duplicate's declaration.
139
+ stack.output("#{id.gsub(/[^A-Za-z0-9]/, "")}Endpoint", value: url)
140
+ end
141
+
142
+ # The logical ID of the AWS::ApiGateway::RestApi under this construct,
143
+ # so that the API can sit in another resource's depends_on:.
144
+ def logical_id
145
+ @api_resource.logical_id
146
+ end
147
+
148
+ # The API's id: the Ref of the RestApi resource, as the CDK's restApiId
149
+ # is the resource's ref (restapi.ts:1024).
150
+ def rest_api_id
151
+ Fn.ref(@api_resource)
152
+ end
153
+
154
+ # The invoke URL of the prod stage, as the CDK's url and its Endpoint
155
+ # output write it (restapi.ts, urlForPath).
156
+ def url
157
+ Fn.join("", [
158
+ "https://",
159
+ Fn.ref(@api_resource),
160
+ ".execute-api.",
161
+ Fn.ref("AWS::Region"),
162
+ ".",
163
+ Fn.ref("AWS::URLSuffix"),
164
+ "/",
165
+ Fn.ref(@stage_resource),
166
+ "/"
167
+ ])
168
+ end
169
+
170
+ private
171
+
172
+ def valid_handler(handler)
173
+ return handler if handler.respond_to?(:arn)
174
+
175
+ raise UsageError, "#{path}: handler takes a function with an arn, got #{handler.inspect}"
176
+ end
177
+
178
+ def valid_name(name)
179
+ return name if name.is_a?(String) && !name.empty?
180
+
181
+ raise UsageError, "#{path}: rest_api_name must be a non-empty String, got #{name.inspect}"
182
+ end
183
+
184
+ def valid_stage_name(name)
185
+ return name if name.is_a?(String) && !name.empty?
186
+
187
+ raise UsageError, "#{path}: stage_name must be a non-empty String, got #{name.inspect}"
188
+ end
189
+
190
+ def valid_authorization(authorization)
191
+ value = authorization.is_a?(Symbol) ? authorization.name.upcase : authorization
192
+ return value if AUTHORIZATION_TYPES.include?(value)
193
+
194
+ raise UsageError, "#{path}: authorization takes #{AUTHORIZATION_TYPES.map(&:inspect).join(", ")}, " \
195
+ "got #{authorization.inspect}"
196
+ end
197
+
198
+ # The ANY method on one resource: HttpMethod, ResourceId, RestApiId,
199
+ # AuthorizationType and the Lambda proxy integration, the properties the
200
+ # CDK's method writes (method.ts:246-267) for this shape.
201
+ def method_properties(resource_id)
202
+ {
203
+ "HttpMethod" => "ANY",
204
+ "ResourceId" => resource_id,
205
+ "RestApiId" => Fn.ref(@api_resource),
206
+ "AuthorizationType" => @authorization,
207
+ "Integration" => {
208
+ "Type" => "AWS_PROXY",
209
+ "IntegrationHttpMethod" => "POST",
210
+ "Uri" => Fn.sub(INVOKE_PATH, "FunctionArn" => @handler.arn)
211
+ }
212
+ }
213
+ end
214
+
215
+ # Eight hex characters of SHA-256 over the canonical JSON of the data,
216
+ # the shape unique_name uses for its suffix. The method set and the
217
+ # API's own properties are the CDK's hashComponents
218
+ # (deployment.ts:184-202).
219
+ def hash_of(*data)
220
+ Digest::SHA256.hexdigest(data.map { |item| JSON.generate(canonical(item)) }.join)[0, 8]
221
+ end
222
+
223
+ # Keys sorted and stringified, recursively: two Hashes that say the same
224
+ # thing hash the same whatever order they were written in.
225
+ def canonical(value)
226
+ case value
227
+ when Hash then value.to_h { |key, item| [ key.to_s, canonical(item) ] }.sort.to_h
228
+ when Array then value.map { |item| canonical(item) }
229
+ else value
230
+ end
231
+ end
232
+ end
233
+ end
234
+ end
@@ -0,0 +1,92 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+
5
+ module RubyCdk
6
+ module Events
7
+ # A schedule for an EventBridge rule: the port of the CDK's Schedule
8
+ # (aws-events/lib/schedule.ts), read at commit
9
+ # c070afb54b9e4dbddd52a85a21077fe970354985, Apache-2.0.
10
+ #
11
+ # RubyCdk::Events::Schedule.rate(10, :minutes) # "rate(10 minutes)"
12
+ # RubyCdk::Events::Schedule.cron(minute: "0", hour: "8") # "cron(0 8 * * ? *)"
13
+ # RubyCdk::Events::Schedule.expression("rate(1 hour)")
14
+ #
15
+ # The CDK takes a Duration for rate and units are chosen from it - whole
16
+ # days first, then hours, then minutes (schedule.ts:43-51). This tool has
17
+ # no Duration; rate takes the number and the unit directly, the three the
18
+ # CDK's literal path writes, plural (schedule.ts:45-51). A rate of 0 is
19
+ # refused, as the CDK refuses one (schedule.ts:40-42).
20
+ #
21
+ # cron takes the six fields as Strings, with the CDK's defaults: "*" for
22
+ # minute, hour, month and year, "?" for week_day, and day becomes "?"
23
+ # when a week_day is given (schedule.ts:66-77). day and week_day cannot
24
+ # go together (schedule.ts:57-59).
25
+ #
26
+ # What the CDK does that is not here: the warning it annotates on a cron
27
+ # without a minute (schedule.ts:69-72) - this tool's constructs write no
28
+ # annotations; the template is the whole output.
29
+ class Schedule
30
+ # The three units the CDK's literal rate path writes (schedule.ts:45-51).
31
+ UNITS = %i[minutes hours days].freeze
32
+
33
+ # The CDK's Schedule.expression (schedule.ts:29-31): a literal
34
+ # expression, in a format EventBridge recognizes.
35
+ def self.expression(expression)
36
+ unless expression.is_a?(String) && !expression.empty?
37
+ raise UsageError, "Schedule.expression takes a non-empty String, got #{expression.inspect}"
38
+ end
39
+
40
+ new(expression)
41
+ end
42
+
43
+ # A rate, the number and the unit: schedule.ts:34-52. Whole minutes,
44
+ # hours or days, at least one. One takes the singular, as the CDK's
45
+ # makeRate writes it (schedule.ts:163-165): "rate(1 day)",
46
+ # "rate(10 minutes)".
47
+ def self.rate(value, unit = :minutes)
48
+ unless value.is_a?(Integer) && value.positive?
49
+ raise UsageError, "Schedule.rate takes a positive Integer, got #{value.inspect}"
50
+ end
51
+ if UNITS.include?(unit)
52
+ return new("rate(1 #{unit[0..-2]})") if value == 1
53
+
54
+ return new("rate(#{value} #{unit})")
55
+ end
56
+
57
+ raise UsageError, "Schedule.rate takes #{UNITS.map(&:inspect).join(", ")}, got #{unit.inspect}"
58
+ end
59
+
60
+ # A cron, the six fields as Strings (schedule.ts:55-86): "cron(minute
61
+ # hour day month weekDay year)". Fields default to "*" and week_day to
62
+ # "?", and day goes "?" when a week_day names one.
63
+ def self.cron(minute: nil, hour: nil, month: nil, year: nil, day: nil, week_day: nil)
64
+ if day && week_day
65
+ raise UsageError, "Cannot supply both 'day' and 'weekDay', use at most one"
66
+ end
67
+ [ minute, hour, month, year, day, week_day ].each do |field|
68
+ next if field.nil? || field.is_a?(String)
69
+
70
+ raise UsageError, "Schedule.cron takes its fields as Strings, got #{field.inspect}"
71
+ end
72
+
73
+ minute = fallback(minute, "*")
74
+ hour = fallback(hour, "*")
75
+ day = fallback(day, week_day ? "?" : "*")
76
+ week_day = fallback(week_day, "?")
77
+ new("cron(#{minute} #{hour} #{day} #{fallback(month, "*")} #{week_day} #{fallback(year, "*")})")
78
+ end
79
+
80
+ def self.fallback(value, default)
81
+ value.nil? ? default : value
82
+ end
83
+ private_class_method :fallback
84
+
85
+ attr_reader :expression_string
86
+
87
+ def initialize(expression_string)
88
+ @expression_string = expression_string
89
+ end
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,104 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+ require_relative "../fn"
5
+
6
+ module RubyCdk
7
+ module SecretsManager
8
+ # A reference to an existing secret, by name, without a lookup (D-022):
9
+ # the port of the CDK's fromSecretNameV2 and of the SecretValue behind it
10
+ # (aws-secretsmanager/lib/secret.ts:605-622 and
11
+ # core/lib/secret-value.ts:100-135), read at commit
12
+ # c070afb54b9e4dbddd52a85a21077fe970354985, Apache-2.0.
13
+ #
14
+ # secret = RubyCdk::SecretsManager::Secret.from_name("prod/db")
15
+ # function(code: ..., handler: ..., environment: { "DB_PASSWORD" => secret.secret_value })
16
+ # RubyCdk::SecretsManager::Secret.secret_value_from_name("prod/db", json_field: "password")
17
+ #
18
+ # This is not a construct and builds no resource: nothing enters the tree,
19
+ # nothing is looked up, and synthesis calls no AWS. The secret must exist
20
+ # in the account and region the stack deploys to, as the CDK's doc says
21
+ # (secret.ts:597-598). The value is CloudFormation's dynamic reference
22
+ # against the ARN, the string fromSecretNameV2's secretValue resolves
23
+ # (secret.ts:475); the ARN is the CDK's partial ARN of fromSecretNameV2 -
24
+ # "secret" then the name, no generated suffix - built with Fn.sub over
25
+ # CloudFormation's own pseudo parameters, so it works in a stack with no
26
+ # concrete env.
27
+ #
28
+ # A reference-only helper grants nothing by itself: the CDK's grantRead on
29
+ # an imported secret lands on the caller's policy with the caller's own
30
+ # secretsmanager: actions; attach a RubyCdk::IAM::PolicyStatement with
31
+ # secretsmanager:DescribeSecret and secretsmanager:GetSecretValue on the
32
+ # ARN to the role that needs them.
33
+ class Secret
34
+ # The reference, in the CDK's fromSecretNameV2 shape
35
+ # (secret.ts:605-622): a name in, the name, the ARN and the value out.
36
+ def self.from_name(name)
37
+ new(name)
38
+ end
39
+
40
+ # The value, in one call. The CDK's SecretValue.secretsManager
41
+ # (secret-value.ts:100-103) with the key its cfnDynamicReferenceKey
42
+ # joins (secret-value.ts:114-135): five parts, the empty ones left
43
+ # empty. version_stage and version_id cannot go together
44
+ # (secret-value.ts:123-125).
45
+ def self.secret_value_from_name(name, json_field: nil, version_stage: nil, version_id: nil)
46
+ new(name).secret_value(json_field: json_field, version_stage: version_stage, version_id: version_id)
47
+ end
48
+
49
+ # The partial ARN, in one call: the CDK's fromSecretNameV2 partialArn
50
+ # (secret.ts:612-620), arn:<partition>:secretsmanager:<region>:
51
+ # <account>:secret:<name>.
52
+ def self.arn_from_name(name)
53
+ new(name).arn
54
+ end
55
+
56
+ # The reference. The CDK's two refusals of a secret id run here
57
+ # (secret-value.ts:115-121): it must be there, and a name with a colon
58
+ # is an ARN mistake, refused before it becomes an unreadable resolve
59
+ # string.
60
+ def initialize(name)
61
+ raise UsageError, "secretId cannot be empty" if name.nil? || name.empty?
62
+ unless name.start_with?("arn:") || !name.include?(":")
63
+ raise UsageError, "secret id \"#{name}\" is not an ARN but contains \":\""
64
+ end
65
+
66
+ @name = name
67
+ end
68
+
69
+ attr_reader :name
70
+
71
+ # The CDK's partial ARN (secret.ts:612-620). A partial ARN names the
72
+ # secret at deploy whatever suffix Secrets Manager gave it; the doc the
73
+ # CDK quotes (secret.ts:600-603) warns against it in CLI reads, and for
74
+ # policies the CDK writes the ARN with a -?????? suffix in its place.
75
+ def arn
76
+ Fn.sub("arn:${AWS::Partition}:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:${SecretName}",
77
+ "SecretName" => @name)
78
+ end
79
+
80
+ # The resolve string, the CDK's SecretValue.secretsManager against the
81
+ # partial ARN, as fromSecretNameV2's secretValue reads it
82
+ # (secret.ts:475): {{resolve:secretsmanager:arn:<partition>:
83
+ # secretsmanager:<region>:<account>:secret:<name>:SecretString:<json
84
+ # field>:<version stage>:<version id>}}, empty parts left empty
85
+ # (secret-value.ts:127-135). An Fn::Sub, so the ARN's pseudo parameters
86
+ # resolve where the value lands. No json_field reads the whole secret
87
+ # JSON. version_stage and version_id cannot go together
88
+ # (secret-value.ts:123-125).
89
+ def secret_value(json_field: nil, version_stage: nil, version_id: nil)
90
+ if version_stage && version_id
91
+ raise UsageError, "versionStage: '#{version_stage}' and versionId: '#{version_id}' were both provided " \
92
+ "but only one is allowed"
93
+ end
94
+ if json_field && !json_field.is_a?(String)
95
+ raise UsageError, "json_field must be a String, got #{json_field.inspect}"
96
+ end
97
+
98
+ { "Fn::Sub" =>
99
+ "{{resolve:secretsmanager:arn:${AWS::Partition}:secretsmanager:${AWS::Region}:${AWS::AccountId}:" \
100
+ "secret:#{@name}:SecretString:#{json_field}:#{version_stage}:#{version_id}}}" }
101
+ end
102
+ end
103
+ end
104
+ end