Class: Morpheus::Cli::CypherCommand
- Inherits:
-
Object
- Object
- Morpheus::Cli::CypherCommand
- Includes:
- CliCommand
- Defined in:
- lib/morpheus/cli/cypher_command.rb
Instance Attribute Summary
Attributes included from CliCommand
Instance Method Summary collapse
- #connect(opts) ⇒ Object
- #get(args) ⇒ Object
- #handle(args) ⇒ Object
-
#initialize ⇒ CypherCommand
constructor
some appropriate aliases register_subcommands :read => :get, register_subcommands :write => :put register_subcommands :add => :put register_subcommands :delete => :remove register_subcommands :destroy => :destroy.
- #list(args) ⇒ Object
- #put(args) ⇒ Object
- #remove(args) ⇒ Object
Methods included from CliCommand
#apply_options, #build_common_options, #build_option_type_options, #build_standard_add_options, #build_standard_delete_options, #build_standard_get_options, #build_standard_list_options, #build_standard_post_options, #build_standard_put_options, #build_standard_remove_options, #build_standard_update_options, #command_description, #command_name, #default_refresh_interval, #default_sigdig, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #get_subcommand_description, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_bytes_param, #parse_id_list, #parse_list_options, #parse_list_subtitles, #parse_passed_options, #parse_payload, #parse_query_options, #print, #print_error, #println, #prog_name, #puts, #puts_error, #raise_args_error, #raise_command_error, #render_response, #run_command_for_each_arg, #subcommand_aliases, #subcommand_description, #subcommand_usage, #subcommands, #usage, #validate_outfile, #verify_args!, #visible_subcommands
Constructor Details
#initialize ⇒ CypherCommand
some appropriate aliases register_subcommands :read => :get, register_subcommands :write => :put register_subcommands :add => :put register_subcommands :delete => :remove register_subcommands :destroy => :destroy
17 18 19 |
# File 'lib/morpheus/cli/cypher_command.rb', line 17 def initialize() # @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance end |
Instance Method Details
#connect(opts) ⇒ Object
21 22 23 24 25 |
# File 'lib/morpheus/cli/cypher_command.rb', line 21 def connect(opts) @api_client = establish_remote_appliance_connection(opts) # @cypher_interface = @api_client.cypher @cypher_interface = @api_client.cypher end |
#get(args) ⇒ Object
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 |
# File 'lib/morpheus/cli/cypher_command.rb', line 115 def get(args) = {} params = {} value_only = false do_decrypt = false ttl = nil optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[key]") # opts.on(nil, '--decrypt', 'Display the decrypted value') do # do_decrypt = true # end # opts.on(nil, '--metadata', 'Display metadata about the key, such as versions.') do # display_versions = true # end opts.on('-v', '--value', 'Print only the decrypted value.') do value_only = true end opts.on( '-t', '--ttl SECONDS', "Time to live, the lease duration before this key expires. Use if creating new key." ) do |val| ttl = val if val.to_s.empty? || val.to_s == '0' ttl = 0 else ttl = val end end (opts, , [:query, :json, :yaml, :csv, :fields, :outfile, :dry_run, :quiet, :remote]) opts. = "Read a cypher item and display the decrypted value." + "\n" + "[key] is required. This is the cypher key to read." + "\n" + "Use --ttl to specify a ttl if expecting cypher engine to automatically create the key." 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() begin item_key = args[0] if ttl params["ttl"] = ttl end @cypher_interface.setopts() if [:dry_run] print_dry_run @cypher_interface.dry.get(item_key, params) return 0 end params.merge!(()) json_response = @cypher_interface.get(item_key, params) render_result = render_with_format(json_response, ) if render_result return 0 end cypher_item = json_response['cypher'] decrypted_value = json_response["data"] data_type = decrypted_value.is_a?(String) ? 'string' : 'object' if value_only print cyan if decrypted_value.is_a?(Hash) puts as_json(decrypted_value) else puts decrypted_value.to_s end print reset return 0 end print_h1 "Cypher Key", [], print cyan # This response does contain cypher too though. if cypher_item.empty? puts_error "Cypher data not found in response" return 1 end description_cols = { #"ID" => 'id', "Key" => lambda {|it| it["itemKey"] }, "TTL" => lambda {|it| format_expiration_ttl(it["expireDate"]) }, # "Type" => lambda {|it| # data_type # }, "Expiration" => lambda {|it| format_expiration_date(it["expireDate"]) }, # "Date Created" => lambda {|it| format_local_dt(it["dateCreated"]) }, "Last Updated" => lambda {|it| format_local_dt(it["lastUpdated"]) }, "Last Accessed" => lambda {|it| format_local_dt(it["lastAccessed"]) } } if cypher_item["expireDate"].nil? description_cols.delete("Expires") end print_description_list(description_cols, cypher_item) # print_h2 "Value", options # print_h2 "Data", options print_h2 "Data (#{data_type})", if decrypted_value print cyan if decrypted_value.is_a?(String) # attempt to parse and render as_json if decrypted_value.to_s[0] == '{' && decrypted_value.to_s[-1] == '}' begin json_value = JSON.parse(decrypted_value) puts as_json(json_value) rescue => ex Morpheus::Logging::DarkPrinter.puts "Failed to parse cypher value '#{decrypted_value}' as JSON. Error: #{ex}" if Morpheus::Logging.debug? puts decrypted_value end else puts decrypted_value end else puts as_json(decrypted_value) end else puts "No data found." end print reset, "\n" return 0 rescue RestClient::Exception => e print_rest_exception(e, ) return 1 end end |
#handle(args) ⇒ Object
27 28 29 |
# File 'lib/morpheus/cli/cypher_command.rb', line 27 def handle(args) handle_subcommand(args) end |
#list(args) ⇒ Object
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 |
# File 'lib/morpheus/cli/cypher_command.rb', line 31 def list(args) = {} params = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[key]") # opts.on('--details', '--details', "Show more details." ) do # options[:details] = true # end (opts, , [:list, :query, :json, :yaml, :csv, :fields, :json, :dry_run, :remote]) opts. = "List cypher keys." + "\n" + "[key] is optional. This is the cypher key or path to search for." end optparse.parse!(args) connect() 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 item_key = args[0] begin params.merge!(()) @cypher_interface.setopts() if [:dry_run] print_dry_run @cypher_interface.dry.list(item_key, params) return 0 end json_response = @cypher_interface.list(item_key, params) if [:json] puts as_json(json_response, ) return 0 elsif [:yaml] puts as_yaml(json_response, ) return 0 elsif [:csv] puts records_as_csv([json_response], ) return 0 end cypher_items = json_response["cypherItems"] || json_response["cyphers"] cypher_data = json_response["data"] title = "Morpheus Cypher Key List" subtitles = [] subtitles += parse_list_subtitles() if item_key subtitles << "Key: #{item_key}" end print_h1 title, subtitles, cypher_keys = json_response["data"] ? json_response["data"]["keys"] : [] if cypher_keys.nil? || cypher_keys.empty? if item_key print cyan,"No cypher items found for '#{item_key}'.",reset,"\n" end else cypher_columns = { "KEY" => lambda {|it| it["itemKey"] }, # "LEASE REMAINING" => lambda {|it| # format_lease_remaining(it["expireDate"]) # }, "TTL" => lambda {|it| format_expiration_ttl(it["expireDate"]) }, "EXPIRATION" => lambda {|it| format_expiration_date(it["expireDate"]) }, # "DATE CREATED" => lambda {|it| format_local_dt(it["dateCreated"]) }, "LAST UPDATED" => lambda {|it| format_local_dt(it["lastUpdated"]) }, "LAST ACCESSED" => lambda {|it| format_local_dt(it["lastAccessed"]) } } print cyan print as_pretty_table(cypher_items, cypher_columns, ) print reset # print_results_pagination({size:cypher_keys.size,total:cypher_keys.size.to_i}) print_results_pagination(json_response) end print reset,"\n" return 0 rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#put(args) ⇒ Object
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 294 295 296 297 298 299 300 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 |
# File 'lib/morpheus/cli/cypher_command.rb', line 248 def put(args) usage = <<-EOT Usage: morpheus #{command_name} put [key] [value] [options] to store a string. morpheus #{command_name} put [key] [k=v] [k=v] [options] to store an object. EOT = {} params = {} item_key = nil item_value = nil ttl = nil no_overwrite = nil optparse = Morpheus::Cli::OptionParser.new do |opts| # opts.banner = subcommand_usage("[key] [value]\n\t[key] [k=v] [k=v] [k=v]") opts. = usage opts.on( '--key KEY', String, "Key. This can also be passed as the first argument." ) do |val| item_key = val end opts.on( '-v', '--value VALUE', "Secret value. This can be used to store a string instead of an object, and can also be passed as the second argument." ) do |val| item_value = val end # opts.on( '--type VALUE', String, "Type, default is based on key engine, string or object" ) do |val| # params['type'] = val # end opts.on( '-t', '--ttl SECONDS', "Time to live, the lease duration before this key expires." ) do |val| ttl = val if val.to_s.empty? || val.to_s == '0' ttl = 0 else ttl = val end end # opts.on( '--no-overwrite', '--no-overwrite', "Do not overwrite existing keys. Existing keys are overwritten by default." ) do # params['overwrite'] = false # end (opts, , [:auto_confirm, :options, :payload, :query, :json, :yaml, :csv, :fields, :outfile, :dry_run, :quiet, :remote]) opts. = "Create or update a cypher key." + "\n" + "[key] is required. This is the key of the cypher being created or updated. The key includes the mount prefix eg. secret/hello" + "\n" + "[value] is required for some cypher engines, such as secret. This is the secret value or k=v pairs being stored. Supports 1-N arguments." + "\n" + "If a single [value] is passed, it is stored as type string." + "\n" + "If more than one [value] is passed, the format is expected to be k=v and the value will be stored as an object." + "\n" + "The --value option can be used to store a string value." + "\n" + "The --payload option can be used to store an object." end optparse.parse!(args) # if args.count < 1 # print_error Morpheus::Terminal.angry_prompt # puts_error "wrong number of arguments, expected 1-N and got #{args.count}\n#{optparse}" # return 1 # end connect() params.merge!(()) # parse arguments like [value] or [k=v] if args.count == 0 # prompt for key and value elsif args.count == 1 item_key = args[0] # prompt for value elsif args.count == 2 item_key = args[0] item_value = args[1] # expecting [value] or [k=v] item_value_object = {} item_value_pair = item_value.split("=") if item_value_pair.size == 2 item_value_object[item_value_pair[0].to_s] = item_value_pair[1] item_value = item_value_object else # item_value = item_value end elsif args.count > 2 item_key = args[0] item_value = args[1] # expecting [k=v] [k=v] item_value_object = {} args[1..(args.size-1)].each do |arg| item_value_pair = arg.split("=") item_value_object[item_value_pair[0].to_s] = item_value_pair[1] end item_value = item_value_object end # this is redunant and silly, refactor soon # Key prompt if item_key [:options]['key'] = item_key end if item_key.nil? v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'key', 'fieldLabel' => 'Key', 'type' => 'text', 'required' => true, 'description' => cypher_key_help}], [:options]) item_key = v_prompt['key'] end payload = nil if [:payload] payload = [:payload] payload.deep_merge!([:options].reject {|k,v| k.is_a?(Symbol) || ['key','value'].include?(k)}) if [:options] && [:options].keys.size > 0 else # merge -O options into normally parsed options params.deep_merge!([:options].reject {|k,v| k.is_a?(Symbol) || ['key','value'].include?(k)}) if [:options] && [:options].keys.size > 0 # Value prompt value_is_required = false cypher_mount_type = item_key.split("/").first if ["secret","tfvars"].include?(cypher_mount_type) value_is_required = true end # todo: read value from STDIN shall we? # cool, we got value as arguments like foo=bar if args.count > 1 # parse one and only arg as the value like password/mine mypassword123 if args.count == 2 && args[1].split("=").size() == 1 item_value = args[1] elsif args.count > 1 # parse args as key value pairs like secret/config foo=bar thing=myvalue value_arguments = args[1..-1] value_arguments_map = {} value_arguments.each do |value_argument| value_pair = value_argument.split("=") value_arguments_map[value_pair[0]] = value_pair[1] ? value_pair[1..-1].join("=") : nil end item_value = value_arguments_map end else # Prompt for a single text value to be sent as {"value":"my secret"} if value_is_required [:options]['value'] = item_value if item_value v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'value', 'fieldLabel' => 'Value', 'type' => 'text', 'required' => value_is_required, 'description' => "Secret value for this cypher"}], [:options]) item_value = v_prompt['value'] end end # make sure not to pass a value for these or it will not save them. # if ['uuid','key','password'].include?(cypher_mount_type) # item_value = nil # end # construct payload # payload = { # 'cypher' => params # } payload = {} # if value is valid json, then the payload IS the value if item_value.is_a?(String) && item_value.to_s[0] == '{' && item_value.to_s[-1] == '}' begin json_object = JSON.parse(item_value) item_value = json_object rescue => ex Morpheus::Logging::DarkPrinter.puts "Failed to parse cypher value '#{item_value}' as JSON. Error: #{ex}" if Morpheus::Logging.debug? raise_command_error "Failed to parse cypher value as JSON: #{item_value}" # return 1 end else # it is just a string if item_value.is_a?(String) params['type'] = 'string' #params["value"] = item_value payload["value"] = item_value elsif item_value.nil? payload = {} else item_value # great, a Hash I hope payload = item_value end end end # prompt for Lease [:options]['ttl'] = ttl if ttl v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'ttl', 'fieldLabel' => 'Lease (TTL in seconds)', 'type' => 'text', 'required' => false, 'description' => cypher_ttl_help, 'defaultValue' => '0'}], [:options]) ttl = v_prompt['ttl'] if ttl params['ttl'] = ttl #payload["ttl"] = ttl end @cypher_interface.setopts() if [:dry_run] print_dry_run @cypher_interface.dry.create(item_key, params, payload) return end existing_cypher = nil json_response = @cypher_interface.list(item_key) if json_response["data"] && json_response["data"]["keys"] existing_cypher = json_response["data"]["keys"].find {|k| k == item_key } end if existing_cypher unless [:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to overwrite the cypher key #{item_key}?") return 9, "aborted command" end end json_response = @cypher_interface.create(item_key, params, payload) render_result = render_with_format(json_response, ) if render_result return 0 end #print_green_success "Cypher #{item_key} updated" # print_green_success "Wrote cypher #{item_key}" print_green_success "Success! Data written to: #{item_key}" # should print without doing get, because that can use a token. cypher_item = json_response['cypher'] get_args = [item_key] + ([:remote] ? ["-r",[:remote]] : []) get(get_args) return 0 end |
#remove(args) ⇒ Object
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 |
# File 'lib/morpheus/cli/cypher_command.rb', line 456 def remove(args) = {} params = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[key]") (opts, , [:auto_confirm, :json, :dry_run, :quiet, :remote]) opts. = "Delete a cypher." + "\n" + "[key] is required. This is the cypher key to be deleted." 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() begin item_key = args[0] cypher_item = find_cypher_by_key(item_key) return 1 if cypher_item.nil? unless [:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the cypher #{item_key}?") return 9, "aborted command" end @cypher_interface.setopts() if [:dry_run] print_dry_run @cypher_interface.dry.destroy(item_key, params) return end json_response = @cypher_interface.destroy(item_key, params) if [:json] puts as_json(json_response, ) elsif ![:quiet] print_green_success "Deleted cypher #{item_key}" # list([]) end return 0 rescue RestClient::Exception => e print_rest_exception(e, ) return 1 end end |