forked from inspec/inspec-alicloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
alicloud_backend.rb
267 lines (227 loc) · 8.13 KB
/
alicloud_backend.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# frozen_string_literal: true
require "aliyunsdkcore"
require "aliyun/oss"
require "rspec/expectations"
# AliCloud Inspec Backend Classes
#
# Class to manage the AliCloud connection, instantiates all required clients for inspec resources
#
class AliCloudConnection
def initialize(params)
params = {} if params.nil?
if params.is_a?(Hash)
# TODO: look into this a bit more below is the original code from AWS
# it does not look like we implement client_args at this point
# this was stopping us from passing a region parameter as params.fetch(:client_args, nil)
# always returns nill
# @client_args = params.fetch(:client_args, nil)
# replacement for now
@client_args = params
end
@cache = {}
end
def alicloud_client(api:, api_version:)
region = @client_args.fetch(:region, nil) || ENV["ALICLOUD_REGION"] if @client_args
region ||= ENV["ALICLOUD_REGION"]
endpoint = @client_args.fetch(:endpoint, nil) if @client_args
endpoint ||= if %w{sts ram resourcemanager}.include?(api)
"https://#{api}.aliyuncs.com"
else
"https://#{api}.#{region}.aliyuncs.com"
end
client = RPCClient.new(
access_key_id: ENV["ALICLOUD_ACCESS_KEY"],
access_key_secret: ENV["ALICLOUD_SECRET_KEY"],
security_token: ENV["ALICLOUD_SECURITY_TOKEN"],
endpoint: endpoint,
api_version: api_version
)
AliCloudCommonClient.new(client)
end
def aliyun_oss_client
region = @client_args.fetch(:region, nil) || ENV["ALICLOUD_REGION"] if @client_args
region ||= ENV["ALICLOUD_REGION"]
endpoint = "https://oss-#{region}.aliyuncs.com"
Aliyun::OSS::Client.new(
endpoint: endpoint,
access_key_id: ENV["ALICLOUD_ACCESS_KEY"],
access_key_secret: ENV["ALICLOUD_SECRET_KEY"],
sts_token: ENV["ALICLOUD_SECURITY_TOKEN"]
)
end
def unique_identifier
# use alicloud account id
caller_identity = sts_client.request(action: "GetCallerIdentity")
caller_identity["AccountId"]
end
# Client convenience methods
def actiontrail_client
alicloud_client(api: "actiontrail", api_version: "2017-12-04")
end
def slb_client
alicloud_client(api: "slb", api_version: "2014-05-15")
end
def ecs_client
alicloud_client(api: "ecs", api_version: "2014-05-26")
end
def oss_client
aliyun_oss_client
end
def sts_client
alicloud_client(api: "sts", api_version: "2015-04-01")
end
def ram_client
alicloud_client(api: "ram", api_version: "2015-05-01")
end
def rm_client
alicloud_client(api: "resourcemanager", api_version: "2020-03-31")
end
def vpc_client
alicloud_client(api: "vpc", api_version: "2016-04-28")
end
end
# an AliCloud RPCClient Wrapper to handle pagination response
class AliCloudCommonClient
def initialize(client)
@client = client
end
# same method signature as RPCClient.request
def request(action:, params: {}, opts: {})
page_number = 1
response_total = nil
loop do
# add PageNumber only for paginated request when PageNumber > 1
params[:PageNumber] = page_number if page_number > 1
response = @client.request(
action: action,
params: params,
opts: opts
)
if response_total.nil?
response_total = response
else
# merge response
response.each_key do |key|
if response[key].instance_of? Hash
response[key].each_key do |key_next|
next unless response[key][key_next].instance_of? Array
# combine the data
response_total[key][key_next] += response[key][key_next]
end
else
# overwrite other values
response_total[key] = response[key]
end
end
end
# stop looping if the response is not paginated or has reached the last page
break if response["PageNumber"].nil? || (page_number * response["PageSize"] >= response["TotalCount"])
page_number += 1
end
response_total
end
end
# Base class for AliCloud resources
class AliCloudResourceBase < Inspec.resource(1)
attr_reader :opts, :alicloud
def initialize(opts)
@opts = opts
# ensure we have a AliCloud connection, resources can choose which of the clients to instantiate
client_args = {}
if opts.is_a?(Hash)
# below allows each resource to optionally and conveniently set a region
client_args[:region] = opts[:region] if opts[:region]
# below allows each resource to optionally and conveniently set an endpoint
client_args[:endpoint] = opts[:endpoint] if opts[:endpoint]
end
# Default region to ALICLOUD_REGION env var - needed in the resource requests for most resources
@opts[:region] ||= ENV["ALICLOUD_REGION"]
@alicloud = AliCloudConnection.new(client_args)
end
# Ensure required parameters have been set to perform backend operations.
# Some resources may require several parameters to be set, in which case use `required`
# Some resources may require at least 1 of n parameters to be set, in which case use `require_any_of`
# If a parameter is entirely optional, use `allow`
def validate_parameters(allow: [], required: nil, require_any_of: nil)
if required
raise ArgumentError, "Expected required parameters as Array of Symbols, got #{required}" unless required.is_a?(Array) && required.all? { |r| r.is_a?(Symbol) }
raise ArgumentError, "#{@__resource_name__}: `#{required}` must be provided" unless @opts.is_a?(Hash) && required.all? { |req| @opts.key?(req) && !@opts[req].nil? && @opts[req] != "" }
allow += required
end
if require_any_of
raise ArgumentError, "Expected required parameters as Array of Symbols, got #{require_any_of}" unless require_any_of.is_a?(Array) && require_any_of.all? { |r| r.is_a?(Symbol) }
raise ArgumentError, "#{@__resource_name__}: One of `#{require_any_of}` must be provided." unless @opts.is_a?(Hash) && require_any_of.any? { |req| @opts.key?(req) && !@opts[req].nil? && @opts[req] != "" }
allow += require_any_of
end
allow += %i{region endpoint}
raise ArgumentError, "Scalar arguments not supported" unless defined?(@opts.keys)
raise ArgumentError, "Unexpected arguments found" unless @opts.keys.all? { |a| allow.include?(a) }
raise ArgumentError, "Provided parameter should not be empty" unless @opts.values.all? do |a|
return true if a.class == Integer
!a.empty?
end
true
end
def failed_resource?
@failed_resource ||= false
end
# Intercept AliCloud exceptions
def catch_alicloud_errors
yield # Catch and create custom messages as needed
rescue ArgumentError
Inspec::Log.error "It appears that you have not set your AliCloud credentials."
fail_resource("No AliCloud credentials available")
rescue StandardError => e
Inspec::Log.warn "AliCloud Service Error encountered running a control with Resource #{@__resource_name__}. " \
"Error message: #{e.message}. You should address this error to ensure your controls are " \
"behaving as expected."
@failed_resource = true
nil
end
# Prevent undefined method error by returning nil.
# This will prevent breaking a test when queried a non-existing method.
# @return [NilClass]
# @see https://github.com/inspec/inspec-azure/blob/master/libraries/support/azure/response.rb
def method_missing(method_name, *args, &block)
if respond_to?(method_name)
super
else
NullResponse.new
end
end
# This is to make RuboCop happy.
def respond_to_missing?(*several_variants)
super
end
end
# Ensure to return nil recursively.
# @see https://github.com/inspec/inspec-azure/blob/master/libraries/support/azure/response.rb
#
class NullResponse
def nil?
true
end
alias empty? nil?
def ==(other)
other.nil?
end
alias === ==
alias <=> ==
def key?(_key)
false
end
def method_missing(method_name, *args, &block)
if respond_to?(method_name)
super
else
self
end
end
# This is to make RuboCop happy.
def respond_to_missing?(*several_variants)
super
end
def to_s
nil
end
end