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,163 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+ require_relative "../fn"
5
+ require_relative "grant"
6
+ require_relative "role"
7
+ require_relative "log_group"
8
+
9
+ module RubyCdk
10
+ module Lambda
11
+ # A Lambda function: the port of the CDK's Function
12
+ # (aws-lambda/lib/function.ts), read at commit
13
+ # c070afb54b9e4dbddd52a85a21077fe970354985, Apache-2.0.
14
+ #
15
+ # code = stack.asset.zip(__dir__.to_s, exclude: ["stack.rb"])
16
+ # RubyCdk::Lambda::Function.new(stack, "Fn",
17
+ # code: code, handler: "app.handler")
18
+ #
19
+ # The runtime is a String, never an enum: the vendored model publishes no
20
+ # Runtime list, and the identifier ages. The default is "ruby4.0", set on
21
+ # 2026-11-26 from AWS's supported-runtimes page (deprecation 2029-03-31;
22
+ # the previous default, ruby3.4, is deprecated a year earlier); when AWS
23
+ # retires it, pass runtime: with the current one. The
24
+ # function's role is the CDK's ServiceRole default (function.ts:1038):
25
+ # trusted by lambda.amazonaws.com, carrying the
26
+ # AWSLambdaBasicExecutionRole managed policy that gives the function its
27
+ # CloudWatch Logs permissions - or pass role: with an IAM::Role built
28
+ # before, and grants to that role land on it.
29
+ #
30
+ # Where this tool differs from the CDK (architecture section 7 wins; the
31
+ # rows are listed in section 21):
32
+ #
33
+ # - The function's log group is a real AWS::Logs::LogGroup of this stack,
34
+ # named /aws/lambda/<function name> when the function has a literal
35
+ # name, kept for 731 days by default (log_retention:, the LogGroup's
36
+ # own CDK default at the pinned commit), and declared before the
37
+ # function with DependsOn, as the CDK orders an explicit log group. The
38
+ # CDK creates no log group (CloudFormation makes one without retention
39
+ # on first invoke) and its logRetention prop is a custom resource; this
40
+ # tool has no custom resources.
41
+ # - The function resource depends on the role resource as well
42
+ # (function.ts, this.resource.node.addDependency(this.role)).
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.
49
+ class Function < Construct
50
+ # The runtime identifier the examples pin. Dated: 2026-11-26, from AWS's
51
+ # supported-runtimes page. No enum, by design - pass runtime: to move.
52
+ DEFAULT_RUNTIME = "ruby4.0"
53
+
54
+ # The managed policy the CDK's default ServiceRole carries
55
+ # (function.ts:1040, AWSLambdaBasicExecutionRole).
56
+ BASIC_EXECUTION_POLICY_ARN = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
57
+
58
+ # The CDK's invoke action (function-base.ts, addPermission's default).
59
+ INVOKE_ACTION = "lambda:InvokeFunction"
60
+
61
+ attr_reader :runtime, :role, :log_group
62
+
63
+ def initialize(scope, id, code:, handler:, role: nil, runtime: DEFAULT_RUNTIME, function_name: nil,
64
+ memory_size: nil, timeout: nil, environment: {}, description: nil, log_retention: nil, initial_policy: [])
65
+ super(scope, id)
66
+ @runtime = valid_runtime(runtime)
67
+ @handler = valid_handler(handler)
68
+ @code = valid_code(code)
69
+ @function_name = valid_function_name(function_name)
70
+ @role = role || IAM::Role.new(self, "ServiceRole",
71
+ assumed_by: "lambda.amazonaws.com",
72
+ managed_policy_arns: [ BASIC_EXECUTION_POLICY_ARN ])
73
+ # The CDK's initialPolicy (function.ts:1082), statements on the
74
+ # function's role.
75
+ Array(initial_policy).each { |statement| @role.add_to_policy(statement) }
76
+
77
+ # The function's log group: /aws/lambda/<function name> when that name
78
+ # is a literal, else a group without a name (CloudFormation then names
79
+ # it at creation, as it does the one it makes itself).
80
+ log_group_name = @function_name.is_a?(String) ? "/aws/lambda/#{@function_name}" : nil
81
+ @log_group = Logs::LogGroup.new(self, "LogGroup", log_group_name: log_group_name, retention_days: log_retention)
82
+
83
+ @resource = resource("Resource", "AWS::Lambda::Function",
84
+ FunctionName: @function_name,
85
+ Description: description,
86
+ Code: code_location,
87
+ Handler: @handler,
88
+ Runtime: @runtime,
89
+ Role: @role.arn,
90
+ MemorySize: memory_size,
91
+ Timeout: timeout,
92
+ Environment: environment.empty? ? nil : { "Variables" => environment },
93
+ depends_on: [ @role, @log_group ])
94
+ end
95
+
96
+ # The logical ID of the AWS::Lambda::Function under this construct, so
97
+ # that the function can sit in another resource's depends_on:.
98
+ def logical_id
99
+ @resource.logical_id
100
+ end
101
+
102
+ # The function's ARN.
103
+ def arn
104
+ Fn.get_att(@resource, "Arn")
105
+ end
106
+
107
+ # The function's name: the one given, or the Ref of the resource.
108
+ def function_name
109
+ @function_name || Fn.ref(@resource)
110
+ end
111
+
112
+ # Grants lambda:InvokeFunction on this function's ARN to the principal
113
+ # (function-base.ts, grantInvoke): on the qualified ARN and on the
114
+ # unqualified one, as the CDK grants both.
115
+ def grant_invoke(principal)
116
+ Constructs::Grant.add_to_principal(principal, [ INVOKE_ACTION ], [ qualified_arn, arn ])
117
+ end
118
+
119
+ private
120
+
121
+ def valid_runtime(runtime)
122
+ return runtime if runtime.is_a?(String) && !runtime.empty?
123
+
124
+ raise UsageError, "#{path}: the runtime must be an identifier String such as \"#{DEFAULT_RUNTIME}\", got #{runtime.inspect}"
125
+ end
126
+
127
+ def valid_handler(handler)
128
+ return handler if handler.is_a?(String) && !handler.empty?
129
+
130
+ raise UsageError, "#{path}: the handler must be a String such as \"app.handler\", got #{handler.inspect}"
131
+ end
132
+
133
+ # The code is an asset of the stack, whose s3_location is the Code
134
+ # property, or a Hash in CloudFormation's Code shape.
135
+ def valid_code(code)
136
+ return code if code.respond_to?(:s3_location)
137
+ return code if code.is_a?(Hash) && !code.empty?
138
+
139
+ raise UsageError, "#{path}: the code must be an asset of the stack (stack.asset.zip(...)) or a Hash in " \
140
+ "CloudFormation's Code shape, got #{code.inspect}"
141
+ end
142
+
143
+ def valid_function_name(name)
144
+ return nil if name.nil?
145
+ return name if name.is_a?(String) && !name.empty?
146
+
147
+ raise UsageError, "#{path}: the function name must be a non-empty String, got #{name.inspect}"
148
+ end
149
+
150
+ def code_location
151
+ return @code.s3_location if @code.respond_to?(:s3_location)
152
+
153
+ @code
154
+ end
155
+
156
+ # The qualified ARN the CDK's grant also names
157
+ # (function-base.ts, resourceArnsForGrantInvoke and its test).
158
+ def qualified_arn
159
+ Fn.join("", [ arn, ":*" ])
160
+ end
161
+ end
162
+ end
163
+ end
@@ -0,0 +1,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+ require_relative "../fn"
5
+ require_relative "policy_statement"
6
+
7
+ module RubyCdk
8
+ module Constructs
9
+ # What a grant_* method answers: who was granted what, on which resources.
10
+ #
11
+ # The shape is the minimum a policy statement needs, which is what the
12
+ # CDK's Grant is built from too (aws-iam/lib/grant.ts at
13
+ # c070afb54b9e4dbddd52a85a21077fe970354985): addToPrincipal takes the
14
+ # grantee, the actions and the resource ARNs, makes one Allow statement of
15
+ # them and hands it to the grantee's grantPrincipal. This tool has exactly
16
+ # one kind of principal that can carry a statement, IAM::Role, whose
17
+ # grantPrincipal is the role itself (aws-iam/lib/role.ts:462) and whose
18
+ # addToPrincipalPolicy creates the role's DefaultPolicy resource
19
+ # (role.ts:653); Role#add_to_policy is that method.
20
+ #
21
+ # grant = bucket.grant_read(role) # applied: the statement is on the role
22
+ # grant = bucket.grant_read("arn:aws:iam::123456789012:user/alice")
23
+ # # unapplied: attach it yourself
24
+ #
25
+ # statement renders the statement; to_statement is its CloudFormation hash.
26
+ # applied? says whether it already sits on the principal's policy.
27
+ class Grant
28
+ attr_reader :principal_arn, :actions, :resource_arns
29
+
30
+ class << self
31
+ # The port of Grant.addToPrincipal (grant.ts): the statement goes to the
32
+ # principal's own policy when the principal can carry one, and is only
33
+ # returned otherwise. principal is an IAM::Role or an ARN String.
34
+ def add_to_principal(principal, actions, resource_arns)
35
+ grant = new(
36
+ principal_arn: principal_arn_of(principal),
37
+ actions: actions.map(&:dup).freeze,
38
+ resource_arns: Array(resource_arns).map(&:dup).freeze
39
+ )
40
+ return grant.apply_to(principal) if principal.is_a?(IAM::Role)
41
+
42
+ grant
43
+ end
44
+
45
+ private
46
+
47
+ def principal_arn_of(principal)
48
+ return principal.arn if principal.is_a?(IAM::Role)
49
+ return principal if principal.is_a?(String) && !principal.empty?
50
+
51
+ raise UsageError, "a grant takes an IAM::Role or a principal ARN String, got #{principal.inspect}"
52
+ end
53
+ end
54
+
55
+ def initialize(principal_arn:, actions:, resource_arns:)
56
+ @principal_arn = principal_arn
57
+ @actions = actions
58
+ @resource_arns = resource_arns
59
+ @applied = false
60
+ end
61
+
62
+ # Puts the statement on the role's policy. Answers the grant itself, so a
63
+ # caller can carry on with it; calling it twice adds the statement twice.
64
+ def apply_to(role)
65
+ unless role.is_a?(IAM::Role)
66
+ raise UsageError, "apply_to takes an IAM::Role, got #{role.inspect}"
67
+ end
68
+
69
+ role.add_to_policy(statement)
70
+ @applied = true
71
+ self
72
+ end
73
+
74
+ # The statement of the grant, as the CDK's Grant#statement: Allow, the
75
+ # actions, the resource ARNs, no principal (the role carries its own).
76
+ def statement
77
+ IAM::PolicyStatement.new(actions: @actions, resources: @resource_arns)
78
+ end
79
+
80
+ def to_statement
81
+ statement.to_statement
82
+ end
83
+
84
+ # True when the statement already sits on the principal's policy.
85
+ def applied?
86
+ @applied
87
+ end
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,115 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+ require_relative "../fn"
5
+ require_relative "grant"
6
+
7
+ module RubyCdk
8
+ module Logs
9
+ # A CloudWatch Logs log group: the port of the CDK's LogGroup
10
+ # (aws-logs/lib/log-group.ts), read at commit
11
+ # c070afb54b9e4dbddd52a85a21077fe970354985, Apache-2.0.
12
+ #
13
+ # RubyCdk::Logs::LogGroup.new(stack, "Logs",
14
+ # log_group_name: "/aws/lambda/my-function", retention_days: 30)
15
+ #
16
+ # Retention defaults to 731 days, the CDK's own default at the pinned
17
+ # commit (log-group.ts: `retentionInDays = RetentionDays.TWO_YEARS`), so a
18
+ # log group out of this tool never keeps logs forever. retention_days:
19
+ # :infinite writes no RetentionInDays, as the CDK's RetentionDays.INFINITE
20
+ # does not, and a retention of 0 or less is refused, as the CDK's
21
+ # RetentionDaysPositive refuses one. The group is a retained type
22
+ # (architecture section 7), which the synthesis gives every
23
+ # AWS::Logs::LogGroup.
24
+ #
25
+ # The grants are the CDK's (aws-logs/lib/log-group-grants.ts, at the same
26
+ # commit): grant_write is logs:CreateLogStream and logs:PutLogEvents on the
27
+ # group's ARN; grant_read adds the read actions on both the group's bare
28
+ # ARN and the GetAtt Arn that carries the stream wildcard, as the CDK's
29
+ # grants.read does. grant_read_write does the two together, which the CDK's
30
+ # grants.actions does with the actions given.
31
+ class LogGroup < Construct
32
+ # The CDK's default retention (log-group.ts, RetentionDays.TWO_YEARS).
33
+ DEFAULT_RETENTION_DAYS = 731
34
+
35
+ # The CDK's write actions (log-group-grants.ts, write).
36
+ WRITE_ACTIONS = [ "logs:CreateLogStream", "logs:PutLogEvents" ].freeze
37
+
38
+ # The CDK's read actions (log-group-grants.ts, read).
39
+ READ_ACTIONS = [
40
+ "logs:FilterLogEvents", "logs:GetLogEvents", "logs:GetLogGroupFields",
41
+ "logs:DescribeLogGroups", "logs:DescribeLogStreams"
42
+ ].freeze
43
+
44
+ attr_reader :retention_days
45
+
46
+ def initialize(scope, id, log_group_name: nil, retention_days: nil)
47
+ super(scope, id)
48
+ @log_group_name = valid_name(log_group_name)
49
+ @retention_days = valid_retention(retention_days)
50
+
51
+ @resource = resource("Resource", "AWS::Logs::LogGroup",
52
+ LogGroupName: @log_group_name,
53
+ RetentionInDays: @retention_days == :infinite ? nil : (@retention_days || DEFAULT_RETENTION_DAYS))
54
+ end
55
+
56
+ # The log group's name: the one given, or the Ref of the resource.
57
+ def log_group_name
58
+ @log_group_name || Fn.ref(@resource)
59
+ end
60
+
61
+ # The logical ID of the AWS::Logs::LogGroup under this construct, so that
62
+ # the group can sit in another resource's depends_on:.
63
+ def logical_id
64
+ @resource.logical_id
65
+ end
66
+
67
+ # The log group's ARN, with the stream wildcard behind it (the GetAtt Arn
68
+ # attribute reads `...:log-group:<name>:*`).
69
+ def arn
70
+ Fn.get_att(@resource, "Arn")
71
+ end
72
+
73
+ # The log group's bare ARN, without the wildcard: the CDK's
74
+ # CfnLogGroup.arnForLogGroup. Built with Fn.sub over CloudFormation's own
75
+ # pseudo parameters, so it works in a stack with no concrete env.
76
+ def group_arn
77
+ Fn.sub("arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:${Group}",
78
+ "Group" => Fn.ref(@resource))
79
+ end
80
+
81
+ # Grants the write actions to the principal (log-group-grants.ts, write).
82
+ def grant_write(principal)
83
+ Constructs::Grant.add_to_principal(principal, WRITE_ACTIONS, [ arn ])
84
+ end
85
+
86
+ # Grants the read actions on the bare ARN and on the GetAtt Arn
87
+ # (log-group-grants.ts, read).
88
+ def grant_read(principal)
89
+ Constructs::Grant.add_to_principal(principal, READ_ACTIONS, [ group_arn, arn ])
90
+ end
91
+
92
+ # Grants both (log-group-grants.ts, actions with the two lists given).
93
+ def grant_read_write(principal)
94
+ Constructs::Grant.add_to_principal(principal, READ_ACTIONS + WRITE_ACTIONS, [ group_arn, arn ])
95
+ end
96
+
97
+ private
98
+
99
+ def valid_name(name)
100
+ return nil if name.nil?
101
+ return name if name.is_a?(String) && !name.empty?
102
+
103
+ raise UsageError, "#{path}: the log group name must be a non-empty String, got #{name.inspect}"
104
+ end
105
+
106
+ def valid_retention(days)
107
+ return DEFAULT_RETENTION_DAYS if days.nil?
108
+ return days if days == :infinite
109
+ return days if days.is_a?(Integer) && days.positive?
110
+
111
+ raise UsageError, "#{path}: retention_days must be a positive number of days or :infinite, got #{days.inspect}"
112
+ end
113
+ end
114
+ end
115
+ end
@@ -0,0 +1,161 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+
5
+ module RubyCdk
6
+ module IAM
7
+ # One statement of an IAM policy: the port of the CDK's PolicyStatement
8
+ # (aws-iam/lib/policy-statement.ts), in the shape the curated constructs
9
+ # need.
10
+ #
11
+ # RubyCdk::IAM::PolicyStatement.new(
12
+ # effect: :allow, # or :deny
13
+ # actions: ["s3:GetObject*"],
14
+ # resources: [bucket.arn, bucket.objects_arn],
15
+ # principals: "lambda.amazonaws.com", # a resource policy needs one
16
+ # conditions: { "Bool" => { "aws:SecureTransport" => "false" } },
17
+ # sid: "AllowPublishThroughSSLOnly"
18
+ # )
19
+ #
20
+ # `to_statement` renders the CloudFormation hash, with the CDK's own key
21
+ # order (policy-statement.ts, toStatementJson; the corpus templates carry
22
+ # it): Action, Condition, Effect, Principal, Resource, Sid. A one-element
23
+ # action or resource list is written as the single string, as the CDK
24
+ # writes it ("Action": "sts:AssumeRole"), and so is the whole statement
25
+ # with only the keys it has.
26
+ #
27
+ # A principal renders as the CDK's principals do
28
+ # (aws-iam/lib/principals/*.ts): "*" stays the bare string (AnyPrincipal in
29
+ # a resource policy), a service name - anything with a dot that is not an
30
+ # ARN - becomes { Service: ... }, an ARN or an account id becomes
31
+ # { AWS: ... } exactly as written (the CDK's AccountPrincipal expands a
32
+ # bare account id to the account's root ARN; write the ARN when you mean
33
+ # the account), and a Hash is taken verbatim.
34
+ class PolicyStatement
35
+ # The two effects, as IAM writes them.
36
+ EFFECTS = { allow: "Allow", deny: "Deny" }.freeze
37
+
38
+ ARN_PREFIX = "arn:"
39
+
40
+ attr_reader :effect, :actions, :resources, :principals, :conditions, :sid
41
+
42
+ def initialize(effect: :allow, actions: [], resources: [], principals: nil, conditions: nil, sid: nil)
43
+ @effect = effect_value(effect)
44
+ @actions = Array(actions).map { |action| text(action, "action") }.freeze
45
+ @resources = Array(resources).map { |resource| value(resource, "resource") }.freeze
46
+ @principals = principals.nil? ? nil : list_of(principals).map { |principal| value(principal, "principal") }.freeze
47
+ @conditions = conditions.nil? ? nil : self.class.stringify(conditions, "conditions").freeze
48
+ @sid = sid.nil? ? nil : text(sid, "sid")
49
+ end
50
+
51
+ # The statement as the template holds it.
52
+ def to_statement
53
+ {
54
+ "Action" => one_or_list(@actions),
55
+ "Condition" => @conditions,
56
+ "Effect" => @effect,
57
+ "Principal" => principals_fragment,
58
+ "Resource" => one_or_list(@resources),
59
+ "Sid" => @sid
60
+ }.compact
61
+ end
62
+
63
+ alias to_h to_statement
64
+
65
+ # How a principal value renders inside a statement: the CDK's principal
66
+ # fragments (see the class comment). A list of principals is merged under
67
+ # their keys, as the CDK merges fragments: two ARNs become
68
+ # { "AWS" => [a, b] }.
69
+ def self.principal_fragment(principal)
70
+ case principal
71
+ when "*"
72
+ "*"
73
+ when Hash
74
+ stringify(principal, "principal")
75
+ when String
76
+ string_principal(principal)
77
+ else
78
+ raise UsageError, "a principal is a String, a Hash or \"*\", got #{principal.inspect}"
79
+ end
80
+ end
81
+
82
+ class << self
83
+ private
84
+
85
+ def string_principal(principal)
86
+ return { "Service" => principal } if principal.include?(".") && !principal.start_with?(ARN_PREFIX)
87
+
88
+ { "AWS" => principal }
89
+ end
90
+ end
91
+
92
+ # Symbols become strings, recursively, without touching the caller's
93
+ # hash. On the class, because the principal fragments are class-level too.
94
+ def self.stringify(hash, what)
95
+ unless hash.is_a?(Hash)
96
+ raise UsageError, "policy statement #{what} must be a Hash, got #{hash.inspect}"
97
+ end
98
+
99
+ hash.to_h do |key, value|
100
+ [ key.to_s, deep_value(value, what) ]
101
+ end
102
+ end
103
+
104
+ def self.deep_value(value, what)
105
+ return stringify(value, what) if value.is_a?(Hash)
106
+ return value.name if value.is_a?(Symbol)
107
+
108
+ value
109
+ end
110
+
111
+ private
112
+
113
+ def effect_value(effect)
114
+ return EFFECTS[effect] if EFFECTS.key?(effect)
115
+ return effect if EFFECTS.value?(effect)
116
+
117
+ raise UsageError, "effect must be :allow or :deny (or \"Allow\"/\"Deny\"), got #{effect.inspect}"
118
+ end
119
+
120
+ def principals_fragment
121
+ return nil if @principals.nil? || @principals.empty?
122
+
123
+ merged = {}
124
+ @principals.each do |principal|
125
+ fragment = self.class.principal_fragment(principal)
126
+ return "*" if fragment == "*"
127
+
128
+ fragment.each do |key, value|
129
+ merged[key] = merged.key?(key) ? Array(merged[key]).push(value) : value
130
+ end
131
+ end
132
+ merged
133
+ end
134
+
135
+ # One value is the value itself, several are the list, none is nothing:
136
+ # how the CDK writes Action and Resource.
137
+ def one_or_list(values)
138
+ return nil if values.empty?
139
+
140
+ values.length == 1 ? values.first : values
141
+ end
142
+
143
+ def text(value, what)
144
+ return value if value.is_a?(String) && !value.empty?
145
+
146
+ raise UsageError, "a policy statement's #{what} must be a non-empty String, got #{value.inspect}"
147
+ end
148
+
149
+ # Array() would take a Hash apart: one principal Hash is one principal.
150
+ def list_of(value)
151
+ value.is_a?(Array) ? value : [ value ]
152
+ end
153
+
154
+ def value(input, what)
155
+ return input if input.is_a?(String) || input.is_a?(Hash) || input.is_a?(Array)
156
+
157
+ raise UsageError, "a policy statement's #{what} must be a String, a Hash or an Array, got #{input.inspect}"
158
+ end
159
+ end
160
+ end
161
+ end
@@ -0,0 +1,118 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+ require_relative "../fn"
5
+ require_relative "grant"
6
+
7
+ module RubyCdk
8
+ module SQS
9
+ # An SQS queue: the port of the CDK's Queue (aws-sqs/lib/queue.ts), read
10
+ # at commit c070afb54b9e4dbddd52a85a21077fe970354985, Apache-2.0.
11
+ #
12
+ # RubyCdk::SQS::Queue.new(stack, "Jobs",
13
+ # queue_name: "jobs", visibility_timeout: 60, retention: 3_600)
14
+ #
15
+ # fifo: true marks the queue FIFO - the queue name then has to end in
16
+ # .fifo, as SQS requires, and the CDK's own naming rule appends the suffix
17
+ # when it is missing. A queue is not a retained type (architecture
18
+ # section 7): nothing is written where the CDK writes Delete on both
19
+ # policies, because the queue is deleted all the same.
20
+ #
21
+ # The grants are the CDK's (aws-sqs/lib/queue-base.ts and its tests, at the
22
+ # pinned commit): consume is ReceiveMessage, ChangeMessageVisibility,
23
+ # GetQueueUrl, DeleteMessage and GetQueueAttributes; send is SendMessage,
24
+ # GetQueueAttributes and GetQueueUrl; purge is PurgeQueue,
25
+ # GetQueueAttributes and GetQueueUrl; and grant takes any actions given.
26
+ # All on the queue's ARN, to the principal's own policy - the CDK's
27
+ # 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.
36
+ class Queue < Construct
37
+ # The CDK's consume actions, in its order (queue-base.ts, its grant test).
38
+ CONSUME_ACTIONS = [
39
+ "sqs:ReceiveMessage", "sqs:ChangeMessageVisibility", "sqs:GetQueueUrl",
40
+ "sqs:DeleteMessage", "sqs:GetQueueAttributes"
41
+ ].freeze
42
+
43
+ # The CDK's send actions, in its order.
44
+ SEND_ACTIONS = [ "sqs:SendMessage", "sqs:GetQueueAttributes", "sqs:GetQueueUrl" ].freeze
45
+
46
+ # The CDK's purge actions, in its order.
47
+ PURGE_ACTIONS = [ "sqs:PurgeQueue", "sqs:GetQueueAttributes", "sqs:GetQueueUrl" ].freeze
48
+
49
+ attr_reader :fifo
50
+
51
+ def initialize(scope, id, queue_name: nil, fifo: false, visibility_timeout: nil, retention: nil)
52
+ super(scope, id)
53
+ @fifo = fifo ? true : false
54
+ @queue_name = queue_name.nil? || queue_name.is_a?(String) && !queue_name.empty? ? queue_name :
55
+ raise(UsageError, "#{path}: queue_name must be a non-empty String, got #{queue_name.inspect}")
56
+ if @queue_name && @fifo && !@queue_name.end_with?(".fifo")
57
+ @queue_name = "#{@queue_name}.fifo"
58
+ end
59
+
60
+ @resource = resource("Resource", "AWS::SQS::Queue",
61
+ QueueName: @queue_name,
62
+ FifoQueue: @fifo || nil,
63
+ VisibilityTimeout: valid_seconds(visibility_timeout, "visibility_timeout"),
64
+ MessageRetentionPeriod: valid_seconds(retention, "retention"))
65
+ end
66
+
67
+ # The logical ID of the AWS::SQS::Queue under this construct, so that the
68
+ # queue can sit in another resource's depends_on:.
69
+ def logical_id
70
+ @resource.logical_id
71
+ end
72
+
73
+ # The queue's ARN.
74
+ def arn
75
+ Fn.get_att(@resource, "Arn")
76
+ end
77
+
78
+ # The queue's URL, the Ref of the resource, as the CDK's queueUrl.
79
+ def queue_url
80
+ Fn.ref(@resource)
81
+ end
82
+
83
+ # Grants the consume actions to the principal (queue-base.ts,
84
+ # grantConsumeMessages).
85
+ def grant_consume_messages(principal)
86
+ Constructs::Grant.add_to_principal(principal, CONSUME_ACTIONS, [ arn ])
87
+ end
88
+
89
+ # Grants the send actions (queue-base.ts, grantSendMessages).
90
+ def grant_send_messages(principal)
91
+ Constructs::Grant.add_to_principal(principal, SEND_ACTIONS, [ arn ])
92
+ end
93
+
94
+ # Grants the purge actions (queue-base.ts, grantPurge).
95
+ def grant_purge(principal)
96
+ Constructs::Grant.add_to_principal(principal, PURGE_ACTIONS, [ arn ])
97
+ end
98
+
99
+ # Grants the actions given (queue-base.ts, grant).
100
+ def grant(principal, *actions)
101
+ Constructs::Grant.add_to_principal(principal, actions, [ arn ])
102
+ end
103
+
104
+ private
105
+
106
+ # Seconds on the wire, as the CDK writes Duration.seconds there. An
107
+ # intrinsic - Fn.ref of a parameter - passes through; only a plain value
108
+ # is checked here.
109
+ def valid_seconds(value, what)
110
+ return nil if value.nil?
111
+ return value if value.is_a?(Integer) && value.positive?
112
+ return value if value.is_a?(Hash)
113
+
114
+ raise UsageError, "#{path}: #{what} must be a positive number of seconds or an intrinsic, got #{value.inspect}"
115
+ end
116
+ end
117
+ end
118
+ end