Class: Morpheus::Cli::CypherCommand

Inherits:
Object
  • Object
show all
Includes:
CliCommand
Defined in:
lib/morpheus/cli/cypher_command.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from CliCommand

#build_common_options, #build_option_type_options, #command_name, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_id_list, #parse_list_options, #parse_list_subtitles, #print, #print_error, #puts, #puts_error, #raise_command_error, #run_command_for_each_arg, #subcommand_aliases, #subcommand_usage, #subcommands, #usage, #verify_access_token!

Constructor Details

#initializeCypherCommand

Returns a new instance of CypherCommand.



13
14
15
# File 'lib/morpheus/cli/cypher_command.rb', line 13

def initialize()
  # @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance
end

Instance Method Details

#add(args) ⇒ Object



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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/morpheus/cli/cypher_command.rb', line 210

def add(args)
  options = {}
  params = {}
  
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    opts.on('--key VALUE', String, "Key for this cypher") do |val|
      params['itemKey'] = val
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :quiet, :remote])
    opts.footer = "Create a new cypher."
  end
  optparse.parse!(args)
  if args.count > 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 0-1 and got #{args.count}\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      # merge -O options into normally parsed options
      params.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options] && options[:options].keys.size > 0
      
      # support [key] as first argument
      if args[0]
        params['itemKey'] = args[0]
      end
      # Key
      if !params['itemKey']
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'itemKey', 'fieldLabel' => 'Key', 'type' => 'text', 'required' => true, 'description' => cypher_key_help}], options)
        params['itemKey'] = v_prompt['itemKey']
      end

      # Value
      value_is_required = false
      cypher_mount_type = params['itemKey'].split("/").first
      if cypher_mount_type == ["secret", "password"].include?(cypher_mount_type)
        value_is_required = true
      end

      if !params['itemValue']
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'itemValue', 'fieldLabel' => 'Value', 'type' => 'text', 'required' => value_is_required, 'description' => "Value for this cypher"}], options)
        params['itemValue'] = v_prompt['itemValue']
      end

      # Lease
      if !params['leaseTimeout']
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'leaseTimeout', 'fieldLabel' => 'Lease', 'type' => 'text', 'required' => false, 'description' => cypher_lease_help}], options)
        params['leaseTimeout'] = v_prompt['leaseTimeout']
      end
      if !params['leaseTimeout'].to_s.empty?
        params['leaseTimeout'] = params['leaseTimeout'].to_i
      end

      # construct payload
      payload = {
        'cypher' => params
      }
    end

    if options[:dry_run]
      print_dry_run @cypher_interface.dry.create(payload)
      return
    end
    json_response = @cypher_interface.create(payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "Added cypher"
      # list([])
      cypher_item = json_response['cypher']
      get([cypher_item['id']])
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object



17
18
19
20
# File 'lib/morpheus/cli/cypher_command.rb', line 17

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @cypher_interface = @api_client.cypher
end

#decrypt(args) ⇒ Object



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
# File 'lib/morpheus/cli/cypher_command.rb', line 157

def decrypt(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Decrypt the value of a cypher." + "\n" +
                  "[id] is required. This is the id or key of a cypher."
  end
  optparse.parse!(args)
  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 1 and got #{args.count}\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    cypher_item = find_cypher_by_name_or_id(args[0])
    return 1 if cypher_item.nil?
    if options[:dry_run]
      print_dry_run @cypher_interface.dry.decrypt(cypher_item["id"], params)
      return
    end
    
    cypher_item = find_cypher_by_name_or_id(args[0])
    return 1 if cypher_item.nil?

    json_response = @cypher_interface.decrypt(cypher_item["id"], params)
    if options[:json]
      puts as_json(json_response, options, "cypher")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "cypher")
      return 0
    elsif options[:csv]
      puts records_as_csv([json_response["crypt"]], options)
      return 0
    end
    print_h1 "Cypher Decrypt"
    print cyan
    print_description_list({
      "ID" => 'id',
      "Key" => lambda {|it| it["itemKey"] },
      "Value" => lambda {|it| it["itemValue"] }
      }, json_response["cypher"])
    print reset, "\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#get(args) ⇒ Object



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
# File 'lib/morpheus/cli/cypher_command.rb', line 84

def get(args)
  options = {}
  do_decrypt = false
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id]")
    opts.on(nil, '--decrypt', 'Display the decrypted value') do
      do_decrypt = true
    end
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Get details about a cypher." + "\n" +
                  "[id] is required. This is the id or key of a cypher."
  end
  optparse.parse!(args)
  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 1 and got #{args.count}\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    if options[:dry_run]
      if args[0].to_s =~ /\A\d{1,}\Z/
        print_dry_run @cypher_interface.dry.get(args[0].to_i)
      else
        print_dry_run @cypher_interface.dry.list({name:args[0]})
      end
      return
    end
    cypher_item = find_cypher_by_name_or_id(args[0])
    return 1 if cypher_item.nil?
    json_response = {'cypher' => cypher_item}  # skip redundant request
    decrypt_json_response = nil
    if do_decrypt
      decrypt_json_response = @cypher_interface.decrypt(cypher_item["id"])
    end
    # json_response = @cypher_interface.get(cypher_item['id'])
    cypher_item = json_response['cypher']
    if options[:json]
      puts as_json(json_response, options, "cypher")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "cypher")
      return 0
    elsif options[:csv]
      puts records_as_csv([cypher_item], options)
      return 0
    end
    print_h1 "Cypher Details"
    print cyan
    description_cols = {
      "ID" => 'id',
      # what here
      "Key" => lambda {|it| it["itemKey"] },
      #"Value" => lambda {|it| it["value"] || "************" },
      "Lease Remaining" => lambda {|it| format_local_dt(it["expireDate"]) },
      "Date Created" => lambda {|it| format_local_dt(it["dateCreated"]) },
      "Last Accessed" => lambda {|it| format_local_dt(it["lastAccessed"]) }
    }
    print_description_list(description_cols, cypher_item)
    if decrypt_json_response
      print_h2 "Decrypted Value"
      print cyan
      puts decrypt_json_response["cypher"] ? decrypt_json_response["cypher"]["itemValue"] : ""
    end
    print reset, "\n"

    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#handle(args) ⇒ Object



22
23
24
# File 'lib/morpheus/cli/cypher_command.rb', line 22

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



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
# File 'lib/morpheus/cli/cypher_command.rb', line 26

def list(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :json, :dry_run, :remote])
    opts.footer = "List cypher items."
  end
  optparse.parse!(args)
  connect(options)
  begin
    params.merge!(parse_list_options(options))
    if options[:dry_run]
      print_dry_run @cypher_interface.dry.list(params)
      return 0
    end
    json_response = @cypher_interface.list(params)      
    cypher_items = json_response["cyphers"]
    if options[:json]
      puts as_json(json_response, options, "cyphers")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "cyphers")
      return 0
    elsif options[:csv]
      puts records_as_csv(cypher_items, options)
      return 0
    end
    title = "Morpheus Cypher List"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    if cypher_items.empty?
      print cyan,"No cypher items found.",reset,"\n"
    else
      cypher_columns = {
        "ID" => 'id',
        "KEY" => lambda {|it| it["itemKey"] || it["key"] },
        "LEASE REMAINING" => lambda {|it| it['expireDate'] ? format_local_dt(it['expireDate']) : "" },
        "DATED CREATED" => lambda {|it| format_local_dt(it["dateCreated"]) },
        "LAST ACCESSED" => lambda {|it| format_local_dt(it["lastAccessed"]) }
      }
      if options[:include_fields]
        cypher_columns = options[:include_fields]
      end
      print cyan
      print as_pretty_table(cypher_items, cypher_columns, options)
      print reset
      print_results_pagination(json_response)
    end
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove(args) ⇒ Object

def decrypt(args) end



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/morpheus/cli/cypher_command.rb', line 301

def remove(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id]")
    build_common_options(opts, options, [:account, :auto_confirm, :json, :dry_run, :quiet, :remote])
    opts.footer = "Delete a cypher." + "\n" +
                  "[id] is required. This is the id or key of a cypher."
  end
  optparse.parse!(args)

  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 1 and got #{args.count}\n#{optparse}"
    return 1
  end

  connect(options)
  begin
    cypher_item = find_cypher_by_name_or_id(args[0])
    return 1 if cypher_item.nil?
    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the cypher #{cypher_item['itemKey']}?")
      return 9, "aborted command"
    end
    if options[:dry_run]
      print_dry_run @cypher_interface.dry.destroy(cypher_item["id"])
      return
    end
    json_response = @cypher_interface.destroy(cypher_item["id"])
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "Deleted cypher #{cypher_item['itemKey']}"
      # list([])
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end