20 Commits

Author SHA1 Message Date
Norm MacLennan
49dc6c8039 preparing release 2016-05-18 10:01:22 -04:00
Norm MacLennan
a2bdd99eb0 cache-busting 2016-05-18 09:55:34 -04:00
Norm MacLennan
46051e0a15 inch-ci and changelog 2016-05-18 09:35:36 -04:00
Norm MacLennan
0f8b19f38b disabling bundler-audit since we aren't locked 2016-05-18 09:29:19 -04:00
Norm MacLennan
4b4179fba9 Merge pull request #21 from maclennann/master
Cleaning up code. Rubocopping and documenting
2016-05-18 09:17:16 -04:00
Norm MacLennan
245499196c rdocing things 2016-05-18 08:54:47 -04:00
Norm MacLennan
664ca88d41 more rubocopping 2016-05-18 07:45:47 -04:00
Norm MacLennan
ac5b935b89 rubocoppy refactor 2016-05-17 21:21:59 -04:00
Norm MacLennan
ee3b907320 construct additional badges 2016-04-15 08:21:20 -04:00
Norm MacLennan
7433099409 Dependency updates and rubocop fixes 2016-04-15 08:16:40 -04:00
Norm MacLennan
fe6a319b43 cc badges 2016-04-15 07:32:56 -04:00
Norm MacLennan
a98319aebe version 2016-04-15 07:01:46 -04:00
Norm MacLennan
7c154f5bc8 Merge pull request #20 from Cimpress-MCP/get_fieldlabel_value
Get fieldlabel value
2016-04-14 13:46:32 -04:00
Calvin Leung Huang
9fc219d98a Remove extra newline 2016-04-14 13:37:38 -04:00
Calvin Leung Huang
561a523261 Set and use fieldlabel value in zanzibar_options instead 2016-04-14 13:29:43 -04:00
Calvin Leung Huang
ca55a4de57 Set fieldlabel default to Password 2016-04-14 11:30:55 -04:00
Calvin Leung Huang
0da43c9fd3 Uncomment spec test 2016-04-13 14:59:05 -04:00
Calvin Leung Huang
ddb2931f6c Fix case on download_secret_file 2016-04-13 14:55:43 -04:00
Calvin Leung Huang
7cec3f7461 Add spec test 2016-04-13 14:51:43 -04:00
Calvin Leung Huang
7f357ef60d Add get_fieldlabel_value 2016-04-13 14:38:21 -04:00
19 changed files with 426 additions and 198 deletions

21
.codeclimate.yml Normal file
View File

@@ -0,0 +1,21 @@
---
engines:
bundler-audit:
enabled: false
duplication:
enabled: true
config:
languages:
- ruby
fixme:
enabled: true
rubocop:
enabled: true
ratings:
paths:
- Gemfile.lock
- "**.rb"
exclude_paths:
- spec/
- templates/
- doc/

View File

@@ -3,3 +3,7 @@ Metrics/ClassLength:
Metrics/LineLength:
Max: 175
AllCops:
Exclude:
- 'spec/**/*'

24
CHANGELOG.md Normal file
View File

@@ -0,0 +1,24 @@
# Change Log
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
## [Unreleased]
## [0.2.0] - 2016-05-18
### Changed
- Upgraded dependencies
- `rubyntlm`: ~>0.4.0 to ~>0.6.0
- `savon`: ~>2.10.0 to ~>2.11.0
- `rubocop`: ~>0.28.0 to ~>0.39.0
- Lots of rubocop-y code cleanup
- Converted from code climate classic to code climate platform
- Added rake task to run code climate platform locally
- Broke low-level secret server operations into `zanzibar/client`
## [0.1.27] - 2016-04-15
### Added
- `zanzibar get` can fetch field values for fields other than password
- This ability has not been added to Zanzifiles yet.
[0.2.0]: https://github.com/Cimpress-MCP/Zanzibar/compare/v0.1.27...v0.2.0
[Unreleased]: https://github.com/Cimpress-MCP/Zanzibar/compare/v0.2.0...HEAD

View File

@@ -1,5 +1,9 @@
# Zanzibar
[![Gem Version](https://badge.fury.io/rb/zanzibar.svg)](http://badge.fury.io/rb/zanzibar)
[![Code Climate](https://codeclimate.com/github/Cimpress-MCP/zanzibar/badges/gpa.svg?1=1)](https://codeclimate.com/github/Cimpress-MCP/zanzibar)
[![Test Coverage](https://codeclimate.com/github/Cimpress-MCP/zanzibar/badges/coverage.svg)](https://codeclimate.com/github/Cimpress-MCP/zanzibar/coverage)
[![Dependency Status](https://gemnasium.com/badges/github.com/Cimpress-MCP/zanzibar.svg)](https://gemnasium.com/github.com/Cimpress-MCP/zanzibar)
[![Inline docs](http://inch-ci.org/github/cimpress-mcp/zanzibar.svg?branch=master)](http://inch-ci.org/github/cimpress-mcp/zanzibar)
Zanzibar is a utility to retrieve secrets from a Secret Server installation. It supports retrieval of a password, public/private key, or secret attachment.
@@ -98,7 +102,7 @@ When it downloads a file, it gets added to `Zanzifile.resolved`. And next time
`resolved` file, it will not attempt to re-download. `zanzibar update` will attempt
to re-download all secrets.
Subdirectories under the root directory `secret_dir` can be created for individual keys by specifying a `prefix` path for that secret. Secrets will default to be downloaded to the root `secret_dir` directory otherwise.
Subdirectories under the root directory `secret_dir` can be created for individual keys by specifying a `prefix` path for that secret. Secrets will default to be downloaded to the root `secret_dir` directory otherwise.
Note: `zanzibar get` can fetch passwords or files, but `zanzibar bundle` can
only operate on secret files.

View File

@@ -7,5 +7,15 @@ require 'rubocop/rake_task'
task default: [:test]
RSpec::Core::RakeTask.new(:test)
RuboCop::RakeTask.new
task :cc_local do
command = 'docker run '
command << '--interactive --tty --rm '
command << '--env CODECLIMATE_CODE="$PWD" '
command << '--volume "$PWD":/code '
command << '--volume /var/run/docker.sock:/var/run/docker.sock '
command << '--volume /tmp/cc:/tmp/cc '
command << 'codeclimate/codeclimate analyze'
sh command
end

View File

@@ -3,208 +3,175 @@ require 'savon'
require 'io/console'
require 'fileutils'
require 'yaml'
require 'zanzibar/client'
module Zanzibar
##
# Class for interacting with Secret Server
# High-level operations for downloading things from Secret Server
class Zanzibar
##
# @param args{:domain, :wsdl, :pwd, :username, :globals{}}
def initialize(args = {})
if args[:username]
@@username = args[:username]
elsif ENV['ZANZIBAR_USER']
@@username = ENV['ZANZIBAR_USER']
else
@@username = ENV['USER']
end
if args[:wsdl]
@@wsdl = args[:wsdl]
else
@@wsdl = get_wsdl_location
end
if args[:pwd]
@@password = args[:pwd]
elsif ENV['ZANZIBAR_PASSWORD']
@@password = ENV['ZANZIBAR_PASSWORD']
else
@@password = prompt_for_password
end
if args[:domain]
@@domain = args[:domain]
else
@@domain = prompt_for_domain
end
@username = resolve_username(args)
@wsdl = resolve_wsdl(args)
@password = resolve_password(args)
@domain = resolve_domain(args)
args[:globals] = {} unless args[:globals]
init_client(args[:globals])
@client = Client.new(@username, @password, @domain, @wsdl, args[:globals])
end
def get_client_username
@@username
end
def get_client_password
@@password
end
## Initializes the Savon client class variable with the wdsl document location and optional global variables
# @param globals{}, optional
def init_client(globals = {})
globals = {} if globals.nil?
@@client = Savon.client(globals) do
wsdl @@wsdl
end
end
## Gets the user's password if none is provided in the constructor.
##
# Gets the user's password if none is provided in the constructor.
# @return [String] the password for the current user
def prompt_for_password
puts "Please enter password for #{@@username}:"
puts "Please enter password for #{@username}:"
STDIN.noecho(&:gets).chomp.tap do
puts "Using password to login..."
puts 'Using password to login...'
end
end
## Gets the wsdl document location if none is provided in the constructor
##
# Gets the wsdl document location if none is provided in the constructor
# @return [String] the location of the WDSL document
def prompt_for_wsdl_location
puts 'Enter the URL of the Secret Server WSDL:'
STDIN.gets.chomp
end
## Gets the domain of the Secret Server installation if none is provided in the constructor
##
# Gets the domain of the Secret Server installation if none is provided in the constructor
# @return [String] the domain of the secret server installation
def prompt_for_domain
puts 'Enter the domain of your Secret Server:'
STDIN.gets.chomp
end
## Get an authentication token for interacting with Secret Server. These are only good for about 10 minutes so just get a new one each time.
# Will raise an error if there is an issue with the authentication.
# @return the authentication token for the current user.
def get_token
response = @@client.call(:authenticate, message: { username: @@username, password: @@password, organization: '', domain: @@domain })
.hash[:envelope][:body][:authenticate_response][:authenticate_result]
fail "Error generating the authentication token for user #{@@username}: #{response[:errors][:string]}" if response[:errors]
response[:token]
rescue Savon::Error => err
raise "There was an error generating the authentiaton token for user #{@@username}: #{err}"
end
## Get a secret returned as a hash
# Will raise an error if there was an issue getting the secret
# @param [Integer] the secret id
# @return [Hash] the secret hash retrieved from the wsdl
def get_secret(scrt_id, token = nil)
secret = @@client.call(:get_secret, message: { token: token || get_token, secretId: scrt_id }).hash[:envelope][:body][:get_secret_response][:get_secret_result]
fail "There was an error getting secret #{scrt_id}: #{secret[:errors][:string]}" if secret[:errors]
return secret
rescue Savon::Error => err
raise "There was an error getting the secret with id #{scrt_id}: #{err}"
end
## Retrieve a simple password from a secret
##
# Retrieve the value from a field label of a secret
# Will raise an error if there are any issues
# @param [Integer] the secret id
# @return [String] the password for the given secret
def get_password(scrt_id)
secret = get_secret(scrt_id)
# @param [String] the field label to get, defaults to Password
# @return [String] the value for the given field label
def get_fieldlabel_value(scrt_id, fieldlabel = 'Password')
secret = @client.get_secret(scrt_id)
secret_items = secret[:secret][:items][:secret_item]
return get_secret_item_by_field_name(secret_items, 'Password')[:value]
return @client.get_secret_item_by_field_name(secret_items, fieldlabel)[:value]
rescue Savon::Error => err
raise "There was an error getting the password for secret #{scrt_id}: #{err}"
raise "There was an error getting '#{fieldlabel}' for secret #{scrt_id}: #{err}"
end
## Get the password, save it to a file, and return the path to the file.
##
# Retrieve a simple password from a secret
# Calls get get_fieldlabel_value()
# @param [Integer] the secret id
# @return [String] the password for the given secret
def get_password(scrt_id)
get_fieldlabel_value(scrt_id)
end
##
# Get the password, save it to a file, and return the path to the file.
def get_username_and_password_and_save(scrt_id, path, name)
secret_items = get_secret(scrt_id)[:secret][:items][:secret_item]
password = get_secret_item_by_field_name(secret_items, 'Password')[:value]
username = get_secret_item_by_field_name(secret_items, 'Username')[:value]
secret_items = @client.get_secret(scrt_id)[:secret][:items][:secret_item]
password = @client.get_secret_item_by_field_name(secret_items, 'Password')[:value]
username = @client.get_secret_item_by_field_name(secret_items, 'Username')[:value]
save_username_and_password_to_file(password, username, path, name)
return File.join(path, name)
File.join(path, name)
end
def write_secret_to_file(path, secret_response)
File.open(File.join(path, secret_response[:file_name]), 'wb') do |file|
file.puts Base64.decode64(secret_response[:file_attachment])
end
end
## Write the password to a file. Intended for use with a Zanzifile
##
# Write the password to a file. Intended for use with a Zanzifile
def save_username_and_password_to_file(password, username, path, name)
user_pass = {'username' => username.to_s, 'password' => password.to_s}.to_yaml
user_pass = { 'username' => username.to_s, 'password' => password.to_s }.to_yaml
File.open(File.join(path, name), 'wb') do |file|
file.print user_pass
end
end
def get_secret_item_by_field_name(secret_items, field_name)
secret_items.each do |item|
return item if item[:field_name] == field_name
end
end
## Get the secret item id that relates to a key file or attachment.
# Will raise on error
# @param [Integer] the secret id
# @param [String] the type of secret item to get, one of privatekey, publickey, attachment
# @return [Integer] the secret item id
def get_scrt_item_id(scrt_id, type, token)
secret = get_secret(scrt_id, token)
secret_items = secret[:secret][:items][:secret_item]
begin
return get_secret_item_by_field_name(secret_items, type)[:id]
rescue
raise "Unknown type, #{type}."
end
end
## Downloads a file for a secret and places it where Zanzibar is running, or :path if specified
##
# Downloads a file for a secret and places it where Zanzibar is running, or :path if specified
# Raise on error
# @param [Hash] args, :scrt_id, :type (one of "Private Key", "Public Key", "Attachment"), :scrt_item_id - optional, :path - optional
def download_secret_file(args = {})
token = get_token
FileUtils.mkdir_p(args[:path]) if args[:path]
path = args[:path] ? args[:path] : '.' ## The File.join below doesn't handle nils well, so let's take that possibility away.
begin
response = @@client.call(:download_file_attachment_by_item_id, message:
{ token: token, secretId: args[:scrt_id], secretItemId: args[:scrt_item_id] || get_scrt_item_id(args[:scrt_id], args[:type], token) })
.hash[:envelope][:body][:download_file_attachment_by_item_id_response][:download_file_attachment_by_item_id_result]
fail "There was an error getting the #{args[:type]} for secret #{args[:scrt_id]}: #{response[:errors][:string]}" if response[:errors]
write_secret_to_file(path, response)
return File.join(path, response[:file_name])
rescue Savon::Error => err
raise "There was an error getting the #{args[:type]} for secret #{args[:scrt_id]}: #{err}"
end
response = @client.download_file_attachment_by_item_id(args[:scrt_id], args[:scrt_item_id], args[:type])
raise "There was an error getting the #{args[:type]} for secret #{args[:scrt_id]}: #{response[:errors][:string]}" if response[:errors]
return write_secret_to_file(args[:path], response)
rescue Savon::Error => err
raise "There was an error getting the #{args[:type]} for secret #{args[:scrt_id]}: #{err}"
end
## Methods to maintain backwards compatibility
##
# Download a private key secret
# @deprecated
def download_private_key(args = {})
args[:type] = 'Private Key'
download_secret_file(args)
end
##
# Download a public key secret
# @deprecated
def download_public_key(args = {})
args[:type] = 'Public Key'
download_secret_file(args)
end
##
# Download an arbitrary secret attachment
# @deprecated
def download_attachment(args = {})
args[:type] = 'Attachment'
download_secret_file(args)
end
private
def make_or_find_path(path = nil)
FileUtils.mkdir_p(path) if path
path || '.'
end
def resolve_username(args = {})
if args[:username]
args[:username]
elsif ENV['ZANZIBAR_USER']
ENV['ZANZIBAR_USER']
else
ENV['USER']
end
end
def resolve_wsdl(args = {})
args[:wsdl]
end
def resolve_password(args = {})
if args[:pwd]
args[:pwd]
elsif ENV['ZANZIBAR_PASSWORD']
ENV['ZANZIBAR_PASSWORD']
else
prompt_for_password
end
end
def resolve_domain(args = {})
if args[:domain]
args[:domain]
else
prompt_for_domain
end
end
def write_secret_to_file(path, secret_response)
path = make_or_find_path(path)
filepath = File.join(path, secret_response[:file_name])
File.open(filepath, 'wb') do |file|
file.puts Base64.decode64(secret_response[:file_attachment])
end
filepath
end
end
end

View File

@@ -2,12 +2,18 @@ module Zanzibar
module Actions
# Basic plumbing for all actions
class Base
##
# The options passed in from the Thor action
attr_accessor :options
private :options=
##
# The logger that Thor is using for this run
attr_accessor :logger
private :logger=
##
# Initialize the basic components used by all actions
def initialize(logger, options = {})
self.logger = logger
self.options = options

View File

@@ -6,17 +6,35 @@ module Zanzibar
module Actions
# Download or verify the secrets in a Zanzifile
class Bundle < Base
##
# The settings defined in the Zanzifile
attr_accessor :settings
##
# The unresolved secrets from the Zanzifile
attr_accessor :remote_secrets
##
# The resolved secrets from the Zanzifile.resolved
attr_accessor :local_secrets
##
# Whether to disregard local secrets and re-download regardness
attr_accessor :update
##
# Our Zanzibar client
attr_accessor :zanzibar
##
# An action that will fetch secrets defined in a Zanzifile
def initialize(ui, options, args = {})
super(ui, options)
@update = args[:update]
end
##
# Coordinate downloading to secrets (or skipping ones we already have)
def run
ensure_zanzifile
load_required_secrets
@@ -39,7 +57,7 @@ module Zanzibar
end
def ensure_zanzifile
fail Error, NO_ZANZIFILE_ERROR unless File.exist? ZANZIFILE_NAME
raise Error, NO_ZANZIFILE_ERROR unless File.exist? ZANZIFILE_NAME
debug { "#{ZANZIFILE_NAME} located..." }
end
@@ -47,7 +65,7 @@ module Zanzibar
## Make sure the directory exists and that a .gitignore is there to ignore it
if @settings['secret_dir']
FileUtils.mkdir_p(@settings['secret_dir'])
if !File.exist? "#{@settings['secret_dir']}/.gitignore"
unless File.exist? "#{@settings['secret_dir']}/.gitignore"
File.open("#{@settings['secret_dir']}/.gitignore", 'w') do |file|
file.puts '*'
file.puts '!.gitignore'
@@ -69,7 +87,7 @@ module Zanzibar
def validate_environment
return unless @settings.empty? || @remote_secrets.empty?
fail Error, INVALID_ZANZIFILE_ERROR
raise Error, INVALID_ZANZIFILE_ERROR
end
def load_resolved_secrets
@@ -94,12 +112,9 @@ module Zanzibar
downloaded_secrets = {}
remote_secrets.each do |key, secret|
full_path = secret.has_key?('prefix') ? File.join(@settings['secret_dir'], secret['prefix']) : @settings['secret_dir']
downloaded_secrets[key] = download_one_secret(secret['id'],
secret['label'],
full_path,
args,
secret['name'] || "#{secret['id']}_password")
full_path = secret.key?('prefix') ? File.join(@settings['secret_dir'], secret['prefix']) : @settings['secret_dir']
downloaded_secrets[key] = download_one_secret(secret['id'], secret['label'], full_path,
args, secret_filename(secret))
debug { "Downloaded secret: #{key} to #{@settings['secret_dir']}..." }
end
@@ -110,13 +125,13 @@ module Zanzibar
def download_one_secret(scrt_id, label, path, args, name = nil)
if label == 'Password'
path = zanzibar(args).get_username_and_password_and_save(scrt_id, path, name)
{ path: path, hash: Digest::MD5.file(path).hexdigest }
else
path = zanzibar(args).download_secret_file(scrt_id: scrt_id,
type: label,
path: path)
{ path: path, hash: Digest::MD5.file(path).hexdigest }
type: label,
path: path)
end
{ path: path, hash: Digest::MD5.file(path).hexdigest }
end
def update_resolved_file(new_secrets)
@@ -134,6 +149,10 @@ module Zanzibar
domain: @settings['domain'],
globals: args)
end
def secret_filename(secret)
secret['name'] || "#{secret['id']}_password"
end
end
end
end

View File

@@ -7,41 +7,58 @@ module Zanzibar
module Actions
# Fetch a single secret
class Get < Base
##
# The options to use when initializing our Zanzibar client
attr_accessor :zanibar_options
##
# The id of the secret to download
attr_accessor :scrt_id
##
# Initialize the action
def initialize(ui, options, scrt_id)
super(ui, options)
@scrt_id = scrt_id
@zanzibar_options = {}
end
##
# Ensure we have the options we need and download the secret
def run
construct_options
ensure_options
fetch_secret(@scrt_id, options['filelabel'])
fetch_secret(@scrt_id)
end
def fetch_secret(scrt_id, label = nil)
##
# Actually download the secret
def fetch_secret(scrt_id)
scrt = ::Zanzibar::Zanzibar.new(@zanzibar_options)
if label
if @zanzibar_options[:filelabel]
scrt.download_secret_file(scrt_id: scrt_id,
type: label)
type: @zanzibar_options[:filelabel])
else
scrt.get_password(scrt_id)
scrt.get_fieldlabel_value(scrt_id, @zanzibar_options[:fieldlabel])
end
end
##
# Coalesce our options and some defaults to ensure we are ready to run
def construct_options
@zanzibar_options[:wsdl] = construct_wsdl
@zanzibar_options[:globals] = { ssl_verify_mode: :none } if options['ignoressl']
@zanzibar_options[:domain] = options['domain']
@zanzibar_options[:username] = options['username'] unless options['username'].nil?
@zanzibar_options[:domain] = options['domain'] ? options['domain'] : 'local'
@zanzibar_options[:fieldlabel] = options['fieldlabel'] || 'Password'
@zanzibar_options[:filelabel] = options['filelabel'] if options['filelabel']
end
##
# Construct a WSDL URL from the server hostname if necessary
def construct_wsdl
if options['wsdl'].nil? && options['server']
DEFAULT_WSDL % options['server']
@@ -50,9 +67,11 @@ module Zanzibar
end
end
##
# Make sure a proper WSDL was constructed
def ensure_options
return if @zanzibar_options[:wsdl]
fail Error, NO_WSDL_ERROR
raise Error, NO_WSDL_ERROR
end
end
end

View File

@@ -8,6 +8,8 @@ module Zanzibar
module Actions
# Create a new Zanzifile
class Init < Base
##
# Make sure we don't already have a Zanzifile, then template one
def run
check_for_zanzifile
write_template
@@ -17,7 +19,7 @@ module Zanzibar
def check_for_zanzifile
return unless File.exist?(ZANZIFILE_NAME) && !options['force']
fail Error, ALREADY_EXISTS_ERROR
raise Error, ALREADY_EXISTS_ERROR
end
def write_template
@@ -28,9 +30,12 @@ module Zanzibar
end
end
##
# Allows us to easily feed our options hash
# to an ERB
class TemplateRenderer < OpenStruct
##
# Render an ERB template to a string
def render(template)
ERB.new(template).result(binding)
end

View File

@@ -8,12 +8,18 @@ require 'zanzibar/error'
require 'zanzibar/defaults'
module Zanzibar
# The `zanzibar` binay/thor application main class
##
# The `zanzibar` binary/thor application main class.
# See http://whatisthor.com/ for information on syntax.
class Cli < Thor
include Thor::Actions
##
# The stream to which we are writing messages (usually stdout)
attr_accessor :ui
##
# Initialize the application and set some logging defaults
def initialize(*)
super
the_shell = (options['no-color'] ? Thor::Shell::Basic.new : shell)
@@ -24,11 +30,15 @@ module Zanzibar
debug_header
end
##
# Print the version of the application
desc 'version', 'Display your Zanzibar verion'
def version
say "#{APPLICATION_NAME} Version: #{VERSION}"
end
##
# Generate a new blank Zanzifile
desc 'init', "Create an empty #{ZANZIFILE_NAME} in the current directory."
option 'verbose', type: :boolean, default: false, aliases: :v
option 'wsdl', type: :string, aliases: :w,
@@ -46,21 +56,29 @@ module Zanzibar
run_action { init! }
end
##
# Fetch secrets declared in a local Zanzifle
desc 'bundle', "Fetch secrets declared in your #{ZANZIFILE_NAME}"
option 'verbose', type: :boolean, default: false, aliases: :v
def bundle
run_action { bundle! }
end
desc 'plunder', "Alias to `#{APPLICATION_NAME} bundle`", :hide => true
desc 'plunder', "Alias to `#{APPLICATION_NAME} bundle`", hide: true
option 'verbose', type: :boolean, default: false, aliases: :v
alias_method :plunder, :bundle
alias plunder bundle
desc 'install', "Alias to `#{APPLICATION_NAME} bundle`"
alias_method :install, :bundle
alias install bundle
##
# Redownload Zazifile secrets
desc 'update', "Redownload all secrets in your #{ZANZIFILE_NAME}"
option 'verbose', type: :boolean, default: false, aliases: :v
def update
run_action { update! }
end
@@ -76,8 +94,12 @@ module Zanzibar
desc: 'Don\'t verify Secret Server\'s SSL certificate'
option 'filelabel', type: :string, aliases: :f,
desc: 'Specify a file (by label) to download'
option 'fieldlabel', type: :string, aliases: :l,
desc: 'Specify a field (by label) to get'
option 'username', type: :string, aliases: :u
option 'password', type: :string, aliases: :p
##
# Fetch a single secret specified on the commandline
def get(scrt_id)
run_action { get! scrt_id }
end
@@ -91,6 +113,7 @@ module Zanzibar
@ui.debug { "#{APPLICATION_NAME} Version: #{VERSION}" }
end
##
# Run the specified action and rescue errors we
# explicitly send back to format them
def run_action(&_block)

91
lib/zanzibar/client.rb Normal file
View File

@@ -0,0 +1,91 @@
require 'zanzibar/version'
require 'savon'
require 'io/console'
require 'fileutils'
require 'yaml'
module Zanzibar
##
# Class for performing low-level WSDL actions against Secret Server
class Client
##
# Initializes the Savon client class variable with the wdsl document location and optional global variables
# @param globals{}, optional
def initialize(username, password, domain, wsdl, globals = {})
@username = username
@password = password
@domain = domain
globals = {} if globals.nil?
wsdl_loc = wsdl
@client = Savon.client(globals) do
wsdl wsdl_loc
end
end
##
# Get an authentication token for interacting with Secret Server. These are only good for about 10 minutes so just get a new one each time.
# Will raise an error if there is an issue with the authentication.
# @return the authentication token for the current user.
def generate_token
response = @client.call(:authenticate, message: { username: @username, password: @password, organization: '', domain: @domain })
.hash[:envelope][:body][:authenticate_response][:authenticate_result]
raise "Error generating the authentication token for user #{@username}: #{response[:errors][:string]}" if response[:errors]
response[:token]
rescue Savon::Error => err
raise "There was an error generating the authentiaton token for user #{@username}: #{err}"
end
##
# Get a secret returned as a hash
# Will raise an error if there was an issue getting the secret
# @param [Integer] the secret id
# @return [Hash] the secret hash retrieved from the wsdl
def get_secret(scrt_id, token = nil)
secret = @client.call(:get_secret, message: { token: token || generate_token, secretId: scrt_id }).hash[:envelope][:body][:get_secret_response][:get_secret_result]
raise "There was an error getting secret #{scrt_id}: #{secret[:errors][:string]}" if secret[:errors]
return secret
rescue Savon::Error => err
raise "There was an error getting the secret with id #{scrt_id}: #{err}"
end
##
# Get the secret item id that relates to a key file or attachment.
# Will raise on error
# @param [Integer] the secret id
# @param [String] the type of secret item to get, one of privatekey, publickey, attachment
# @return [Integer] the secret item id
def get_scrt_item_id(scrt_id, type, token)
secret = get_secret(scrt_id, token)
secret_items = secret[:secret][:items][:secret_item]
begin
return get_secret_item_by_field_name(secret_items, type)[:id]
rescue => e
raise "Unknown type, #{type}. #{e}"
end
end
##
# Get an "Attachment"-type file from a secret
# @param [Integer] the id of the secret
# @param [Integer] the id of the attachment on the secret
# @param [String] the type of the item being downloaded
# @return [Hash] contents and metadata of the downloaded file
def download_file_attachment_by_item_id(scrt_id, secret_item_id, item_type, token = nil)
token = generate_token unless token
@client.call(:download_file_attachment_by_item_id, message:
{ token: token, secretId: scrt_id, secretItemId: secret_item_id || get_scrt_item_id(scrt_id, item_type, token) })
.hash[:envelope][:body][:download_file_attachment_by_item_id_response][:download_file_attachment_by_item_id_result]
end
##
# Extract an item from a secret based on field name
def get_secret_item_by_field_name(secret_items, field_name)
secret_items.each do |item|
return item if item[:field_name] == field_name
end
end
end
end

View File

@@ -2,15 +2,25 @@ require 'pathname'
# Definitions for various strings used throughout the gem
module Zanzibar
# The name of the binstub that invoked this code
APPLICATION_NAME = Pathname.new($PROGRAM_NAME).basename
ZANZIFILE_NAME = 'Zanzifile'
RESOLVED_NAME = 'Zanzifile.resolved'
TEMPLATE_NAME = 'templates/Zanzifile.erb'
DEFAULT_SERVER = 'secret.example.com'
DEFAULT_WSDL = 'https://%s/webservices/sswebservice.asmx?wsdl'
# The filename of the Zanzifile
ZANZIFILE_NAME = 'Zanzifile'.freeze
# The filename of the resolved Zanzifile
RESOLVED_NAME = 'Zanzifile.resolved'.freeze
# The template to use when writing the Zanzifile
TEMPLATE_NAME = 'templates/Zanzifile.erb'.freeze
# The default value of the server when writing the Zanzifile
DEFAULT_SERVER = 'secret.example.com'.freeze
# The default WSDL location for the Zanzifile template
DEFAULT_WSDL = 'https://%s/webservices/sswebservice.asmx?wsdl'.freeze
ALREADY_EXISTS_ERROR = "#{ZANZIFILE_NAME} already exists! Aborting..."
NO_WSDL_ERROR = 'Could not construct WSDL URL. Please provide either --server or --wsdl'
NO_ZANZIFILE_ERROR = "You don't have a #{ZANZIFILE_NAME}! Run `#{APPLICATION_NAME} init` first!"
INVALID_ZANZIFILE_ERROR = "Unable to load your #{ZANZIFILE_NAME}. Please ensure it is valid YAML."
# Error thrown when trying to overwrite an existing Zanzifile
ALREADY_EXISTS_ERROR = "#{ZANZIFILE_NAME} already exists! Aborting...".freeze
# Error thrown when unable to construct the WSDL location
NO_WSDL_ERROR = 'Could not construct WSDL URL. Please provide either --server or --wsdl'.freeze
# Error thrown when trying to download secrets from a Zanzifile that doesn't exist
NO_ZANZIFILE_ERROR = "You don't have a #{ZANZIFILE_NAME}! Run `#{APPLICATION_NAME} init` first!".freeze
# Error thrown when a Zanzifile is missing necessary information
INVALID_ZANZIFILE_ERROR = "Unable to load your #{ZANZIFILE_NAME}. Please ensure it is valid YAML.".freeze
end

View File

@@ -1,40 +1,59 @@
require 'rubygems/user_interaction'
module Zanzibar
##
# Prints messages out to stdout
class Shell
##
# The stream to write log messages (usually stdout)
attr_writer :shell
##
# Logging options and initializing stream
def initialize(shell)
@shell = shell
@quiet = false
@debug = ENV['DEBUG']
end
##
# Write a debug message if debug is enabled
def debug(message = nil)
@shell.say(message || yield) if @debug && !@quiet
end
##
# Write an info message unless we have silenced output
def info(message = nil)
@shell.say(message || yield) unless @quiet
end
##
# Ask the user for confirmation unless we have silenced output
def confirm(message = nil)
@shell.say(message || yield, :green) unless @quiet
end
##
# Print a warning
def warn(message = nil)
@shell.say(message || yield, :yellow)
end
##
# Print an error
def error(message = nil)
@shell.say(message || yield, :red)
end
##
# Enable silent mode
def be_quiet!
@quiet = true
end
##
# Enable debug mode
def debug!
@debug = true
end

View File

@@ -1,4 +1,5 @@
# The version of the gem
module Zanzibar
VERSION = '0.1.24'
# The Version of the application
VERSION = '0.2.0'.freeze
end

View File

@@ -24,12 +24,12 @@ describe Zanzibar::Cli do
FakeFS::FileSystem.clone files
stub_request(:any, 'https://www.zanzitest.net/webservices/sswebservice.asmx')
.to_return({body: AUTH_XML, status: 200}).then
.to_return({body: SECRET_WITH_KEY_XML, status: 200}).then
.to_return({body: PRIVATE_KEY_XML, status: 200}).then
.to_return({body: AUTH_XML, status: 200}).then
.to_return({body: SECRET_WITH_KEY_XML, status: 200}).then
.to_return({body: PRIVATE_KEY_XML, status: 200})
.to_return(body: AUTH_XML, status: 200).then
.to_return(body: SECRET_WITH_KEY_XML, status: 200).then
.to_return(body: PRIVATE_KEY_XML, status: 200).then
.to_return(body: AUTH_XML, status: 200).then
.to_return(body: SECRET_WITH_KEY_XML, status: 200).then
.to_return(body: PRIVATE_KEY_XML, status: 200)
Dir.chdir File.join(source_root, 'spec', 'files')
end
@@ -87,9 +87,9 @@ describe Zanzibar::Cli do
WebMock.reset!
stub_request(:any, 'https://www.zanzitest.net/webservices/sswebservice.asmx')
.to_return({body: AUTH_XML, status: 200}).then
.to_return({body: SECRET_WITH_KEY_XML, status: 200}).then
.to_return({body: PRIVATE_KEY_XML, status: 200}).then
.to_return(body: AUTH_XML, status: 200).then
.to_return(body: SECRET_WITH_KEY_XML, status: 200).then
.to_return(body: PRIVATE_KEY_XML, status: 200).then
.to_return(body: AUTH_XML, status: 200).then
.to_return(body: SECRET_WITH_KEY_XML, status: 200).then
.to_return(body: PRIVATE_KEY_XML, status: 200)

View File

@@ -47,6 +47,11 @@ describe Zanzibar::Cli do
expect { subject.get(1234) }.to raise_error.with_message(/#{Zanzibar::NO_WSDL_ERROR}/)
end
it 'should be able to get a field value' do
subject.options = { 'domain' => 'zanzitest.net', 'wsdl' => 'scrt.wsdl', 'fieldlabel' => 'Username' }
expect { subject.get(1234) }.to output(/ZanziUser/).to_stdout
end
it 'should be able to download files' do
WebMock.reset!
stub_request(:any, 'https://www.zanzitest.net/webservices/sswebservice.asmx')

View File

@@ -13,7 +13,7 @@ describe 'Zanzibar Test' do
stub_request(:any, 'https://www.zanzitest.net/webservices/sswebservice.asmx')
.to_return(body: AUTH_XML, status: 200)
expect(client.get_token).to eq('imatoken')
expect(client.instance_variable_get(:@client).generate_token).to eq('imatoken')
end
it 'should get a secret' do
@@ -21,7 +21,7 @@ describe 'Zanzibar Test' do
.to_return(body: AUTH_XML, status: 200).then
.to_return(body: SECRET_XML, status: 200)
expect(client.get_secret(1234)[:secret][:name]).to eq('Zanzi Test Secret')
expect(client.instance_variable_get(:@client).get_secret(1234)[:secret][:name]).to eq('Zanzi Test Secret')
end
it 'should get a password' do
@@ -109,18 +109,18 @@ describe 'Zanzibar Test' do
.to_return(body: AUTH_XML, status: 200).then
.to_return(body: SECRET_XML, status: 200)
client.get_username_and_password_and_save(1234, '.', 'zanziTestCreds')
expect(File.exist? 'zanziTestCreds')
expect(File.read('zanziTestCreds')).to eq({'username' => 'ZanziUser', 'password' => 'zanziUserPassword'}.to_yaml)
File.delete('zanziTestCreds')
client.get_username_and_password_and_save(1234, '.', 'zanziTestCreds')
expect(File.exist? 'zanziTestCreds')
expect(File.read('zanziTestCreds')).to eq({ 'username' => 'ZanziUser', 'password' => 'zanziUserPassword' }.to_yaml)
File.delete('zanziTestCreds')
end
it 'should use environment variables for credentials' do
ENV['ZANZIBAR_USER'] = 'environment_user'
ENV['ZANZIBAR_PASSWORD'] = 'environment_password'
client = Zanzibar::Zanzibar.new(domain: 'zanzitest.net', wsdl: 'spec/scrt.wsdl')
expect(client.get_client_username).to eq(ENV['ZANZIBAR_USER'])
expect(client.get_client_password).to eq(ENV['ZANZIBAR_PASSWORD'])
expect(client.instance_variable_get(:@username)).to eq(ENV['ZANZIBAR_USER'])
expect(client.instance_variable_get(:@password)).to eq(ENV['ZANZIBAR_PASSWORD'])
ENV.delete 'ZANZIBAR_PASSWORD'
ENV.delete 'ZANZIBAR_USER'
end

View File

@@ -14,13 +14,13 @@ Gem::Specification.new do |spec|
spec.license = 'Apache 2.0'
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(/^bin\//) { |f| File.basename(f) }
spec.test_files = spec.files.grep(/^(test|spec|features)\//)
spec.executables = spec.files.grep(%r{^bin\/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)\/})
spec.require_paths = ['lib']
spec.add_development_dependency 'bundler', '~> 1.7'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'rubocop', '~> 0.28.0'
spec.add_development_dependency 'rubocop', '~> 0.39.0'
spec.add_development_dependency 'savon_spec', '~> 0.1.6'
spec.add_development_dependency 'rspec', '~> 3.1.0'
spec.add_development_dependency 'webmock', '~> 1.20.4'
@@ -28,7 +28,7 @@ Gem::Specification.new do |spec|
spec.add_development_dependency 'fakefs', '~> 0.6.4'
spec.add_development_dependency 'simplecov', '~> 0.9.1'
spec.add_runtime_dependency 'savon', '~> 2.10.0'
spec.add_runtime_dependency 'rubyntlm', '~> 0.4.0'
spec.add_runtime_dependency 'savon', '~> 2.11.0'
spec.add_runtime_dependency 'rubyntlm', '~> 0.6.0'
spec.add_runtime_dependency 'thor', '~> 0.19.0'
end