pps_commons 0.1.2

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 21ce97f902f90c72e6419fed798708be8f9e9b8b
4
+ data.tar.gz: 14d88644cd35457d96abf7ddc55149b00914013f
5
+ SHA512:
6
+ metadata.gz: 2347087f700aadc308b644655159832c9ea920cd357088fdaf39e0ffa7331bf702434c57b7a659646fd1a07a821eaa5511408aaacefb0f2036f5bc0792b4c30a
7
+ data.tar.gz: 4f5676db6ecc59e245d1f1fb14c9868dcfb8742f4b035b42440bda0df4616b96c5f804efdd8eecc7821389ae8065893922c8144a27242150540ebaee0b575f94
data/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ .byebug*
10
+ Gemfile.lock
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --require spec_helper
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at adam.phillipps@wgu.edu. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) { |repo_name| "https://git.wgu.edu/projects/OPS/repos/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in pps_commons.gemspec
6
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Adam Phillipps
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,24 @@
1
+ # PPSCommons
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/pps_commons`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'pps_commons'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install pps_commons
22
+
23
+ ## Usage
24
+
data/Rakefile ADDED
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "pps_commons"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,54 @@
1
+ require 'chef-api'
2
+
3
+ module WGU
4
+ module ChefComms
5
+ def self.global_config(client, group_name, message)
6
+ # search through global config indexes for a match
7
+ config =
8
+ client.data_bags.find { |d_b| d_b.name =~ /#{group_name}/ }
9
+
10
+ if config.nil?
11
+ config = client.roles.fetch(group_name)
12
+
13
+ unless config.nil?
14
+ stop = Regexp.union([/for\s/, /with\s/, /using\s/])
15
+ location =
16
+ message.gsub(/.*\sdata\sstore\sunder\s(\w+)\s#{stop}.*/, '\1')
17
+ usable_role =
18
+ config.default_attributes[group_name][location].key?('java_opts')
19
+ end
20
+
21
+ usable_role ? [config, 'role'] : []
22
+ else
23
+ [config, 'data bag']
24
+ end
25
+ end
26
+
27
+ private
28
+ def self.client(config)
29
+ client = ChefAPI::Connection.new(
30
+ client: ENV['CM_CHEF_API_CLIENT'],
31
+ endpoint: config[:endpoint],
32
+ key: config[:key]
33
+ )
34
+
35
+ block_given? ? yield(client) : client
36
+ end
37
+
38
+ def self.clients
39
+ self.client_configs.map do |config|
40
+ block_given? ? yield(self.client(config)) : self.client(config)
41
+ end
42
+ end
43
+
44
+ def self.client_configs(*given)
45
+ endpoints = ENV.keys.select { |k| k =~ /^CM_CHEF_API_ENDPOINT/ }
46
+
47
+ endpoints.map do |endpoint|
48
+ chef_env = endpoint.gsub(/CM_CHEF_API_ENDPOINT_(\w+)$/, '\1')
49
+ key_file = ENV["CM_CHEF_API_KEY_#{chef_env}"]
50
+ { endpoint: ENV[endpoint], key: ::File.expand_path(key_file) }
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,48 @@
1
+ require 'rest-client'
2
+ require 'json'
3
+ require 'byebug'
4
+
5
+ module Commons
6
+ module ClassMethods
7
+ # this tells EventMachine how many threads it can use. There is a lot of Deferrals
8
+ # in this project so it helps to run a higher number.
9
+ # EM defaults to '20', PPS defaults to '40'
10
+ def unleash_the_fury_level
11
+ found = ENV['PPS_THREAD_COUNT'].to_i
12
+ found.eql?(0) ? 40 : found.to_i
13
+ end
14
+
15
+ # search through a hash's nested keys for crap
16
+ def ClassMethods.deep_find(key, object=self, found=nil)
17
+ if object.respond_to?(:key?) && object.key?(key)
18
+ object[key]
19
+ elsif object.respond_to?(:each)
20
+ object.find { |k,v| found = deep_find(key, v) }
21
+ found
22
+ end
23
+ end
24
+ end
25
+
26
+ # TODO: accept a file path instead of somewhere in the gems
27
+ def logger(file = nil)
28
+ if @logger.nil?
29
+ log = ::File.expand_path(file)
30
+ unless ::File.exist?(log)
31
+ log_dir = File.dirname(log)
32
+ unless ::Dir.exist?(log_dir)
33
+ ::Dir.mkdir_p(log_dir)
34
+ end
35
+ ::File.new(log, 'a+')
36
+ end
37
+
38
+ Logger.new(log)
39
+ else
40
+ @logger
41
+ end
42
+ end
43
+
44
+ # instance version of +self.deep_find()+
45
+ def deep_find(key, object=self, found=nil)
46
+ Commons::ClassMethods.deep_find(key, object)
47
+ end
48
+ end
@@ -0,0 +1,121 @@
1
+ require 'byebug'
2
+ require 'dotenv'
3
+ module WGU
4
+ # The DelegationAgent class allows you to pass in a message and move on with
5
+ # life. It does this by understanding the message and deferring the correct
6
+ # methods for later. This class is called from the PPS agents in the work_loop.
7
+ class DelegationAgent
8
+ include PPSCommons
9
+
10
+ attr_accessor :requester
11
+ attr_reader :sentence
12
+ attr_accessor :opperation
13
+ attr_accessor :callback
14
+ attr_accessor :errorback
15
+ attr_accessor :results
16
+
17
+ def initialize(requester, message, connections)
18
+ @results = []
19
+ @requester = requester
20
+ @message = (
21
+ message.kind_of?(WGU::Sentence) ? message.log_entry : message.to_s
22
+ ).strip
23
+ @connections = connections
24
+ @sentence = WGU::Sentence.new(requester, message)
25
+ end
26
+
27
+ # cloudwatch could do something if it saw this line and/or this method could
28
+ # do something like send an email or pagerduty alert etc.
29
+ def alert_human(message)
30
+ logger.info("!!!HUMAN ALERT!!!--->#{message}<---!!!HUMAN ALERT!!!")
31
+ self
32
+ end
33
+
34
+ # Load and include the handler that will be able to do what this message
35
+ # will need, when it's ready to run.
36
+ def _include_handler
37
+ handler, handler_file = _handler_info
38
+
39
+ load(handler_file)
40
+ self.class.send :include, Object.const_get(handler)
41
+ end
42
+
43
+ # use the +@request+, +category+ and config file locations to find the path
44
+ # to the correct handler file and format the correct name for the handler.
45
+ #
46
+ # returns:
47
+ # * +Array+ : Name and path to handler file
48
+ def _handler_info(pr = nil)
49
+ handler_words = [@requester.agent_name, sentence.category, 'handler']
50
+ handler = "WGU::#{handler_words.map(&:capitalize).join}"
51
+ project_dir = if (pr = ENV['PPS_ROOT']).nil?
52
+ assumed_root = File.expand_path(::File.join(__FILE__, '..', '..'))
53
+ assumed_root.split('/')[0..-1]
54
+ else
55
+ pr
56
+ end
57
+ file_name = handler_words.join('_') + '.rb'
58
+ handler_file = File.join(
59
+ *project_dir, @requester.agent_name.to_s, file_name
60
+ )
61
+
62
+ [handler, handler_file]
63
+ end
64
+
65
+ # Create a new +DelegationAgent+ for this message. Inject handler abilities
66
+ # into this newly created +DelegationAgent+. Lastly, set the +opperation+,
67
+ # +callback+ and +errback+ methods on the Delegation agent so that they
68
+ # can be called later on, when they are needed.
69
+ def self.delegate_for(*args)
70
+ new_delegate = Class.new(WGU::DelegationAgent).new(*args)
71
+ new_delegate._include_handler
72
+ new_delegate._set_callbacks
73
+ new_delegate
74
+ end
75
+
76
+ # Collect the actions for this message, so that they can be easily used
77
+ # together, in the correct order
78
+ def callbacks_for_deferral
79
+ [opperation, callback, errorback]
80
+ end
81
+
82
+ def logger
83
+ if @logger.nil?
84
+ logs = ::File.expand_path(::File.join(__FILE__, '../../', 'logs/group.log'))
85
+ unless ::File.exist?(logs)
86
+ log_dir = ::File.expand_path(::File.join(__FILE__, '../..', 'logs'))
87
+ unless ::Dir.exist?(log_dir)
88
+ ::Dir.mkdir_p(log_dir)
89
+ end
90
+ ::File.new(logs, 'a+')
91
+ end
92
+
93
+ Logger.new(logs)
94
+ else
95
+ @logger
96
+ end
97
+ end
98
+
99
+ # Send a message to the appropriate receiver.
100
+ def send_response_to(recipient, results = @results)
101
+ msg = results.kind_of?(WGU::Sentence) ? results.log_entry : "#{results.to_s.strip}\n"
102
+ msg
103
+ logger.info(
104
+ "#{requester.agent_name.capitalize} sending message: \"#{msg}\" to -> #{recipient}"
105
+ )
106
+
107
+ if @requester.agent_name.eql? :broker
108
+ @connections[recipient].receive_data(msg)
109
+ else
110
+ requester.send_data(msg)
111
+ end
112
+
113
+ self
114
+ end
115
+
116
+ private
117
+ def _set_up_logger
118
+ Logger.new('../logs/test.log')
119
+ end
120
+ end
121
+ end
@@ -0,0 +1,182 @@
1
+ require 'pps_commons/commons'
2
+
3
+ module WGU
4
+ class Sentence
5
+ attr_reader :recipient
6
+ attr_reader :message
7
+
8
+ def initialize(recipient, msg)
9
+ @recipient = recipient
10
+ @message = (msg.kind_of?(WGU::Sentence) ? msg.log_entry : msg.to_s)
11
+ @message.strip!
12
+ end
13
+
14
+ def add_need(need)
15
+ with_clause =~ /#{need}/ ? @message : add_need!(need)
16
+ end
17
+
18
+ def add_need!(need)
19
+ if with_clause.empty?
20
+ @message << " with needs #{need}"
21
+ else
22
+ tmp = if with_clause =~ /needs/
23
+ "needs #{need} and"
24
+ else
25
+ "needs #{need}"
26
+ end
27
+
28
+ new_with_clause = "#{tmp} #{with_clause}"
29
+ @message.gsub!(/#{with_clause}/, new_with_clause).strip!
30
+ @message
31
+ end
32
+ end
33
+
34
+ def category
35
+ request? ? :request : :response
36
+ end
37
+
38
+ def has_more_needs?
39
+ !!(message.index(' needs '))
40
+ end
41
+
42
+ # Hostname or ipaddress from message
43
+ def location_information
44
+ if message.scan(/\s([a-z0-9\-]+\.wgu\.edu)\s/).count > 0
45
+ message.gsub(/.+\s([a-z0-9\-]+\.wgu\.edu)\s.+/, '\1')
46
+ elsif message.scan(/(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b)/).count > 0
47
+ message.gsub(/.+(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b).+/, '\1')
48
+ elsif message.scan(/WGU_UT\\[a-z\-0-9]+\s/i).count > 0
49
+ message.gsub(/.+WGU_UT\\([a-z\-0-9]+)\s.*/i, '\1')
50
+ else
51
+ message.gsub(/.+for\s\w+\son\s([\w\-]+)\swith.*/, '\1')
52
+ end
53
+ end
54
+
55
+ def log_entry
56
+ @log_entry || "#{message.to_s}\n"
57
+ end
58
+
59
+ def mark_completed!(need)
60
+ matched_needs = needs.select { |nd| /\!?#{need}/ =~ nd }
61
+ if matched_needs.count > 1
62
+ "alert human #{message} has too many validations that match the name \"#{need}\" so it failed"
63
+ else
64
+ suffix = with_clause[/needs\s\!?#{Regexp.escape(matched_needs.first)}\s?/]
65
+ new_suffix = suffix.gsub(/needs\s/, '')
66
+ message.gsub!(/#{Regexp.escape(suffix)}/, new_suffix).strip!
67
+ words = message.split(' ')
68
+ prefix = words[0..words.index('for')].join(' ')
69
+ message.gsub!(/#{Regexp.escape(prefix)}/, '').strip!
70
+ message
71
+ end
72
+ end
73
+
74
+ def mark_incompleted!(need)
75
+ mark_completed!(need)
76
+ message.gsub!(/(with)?(and)?\s!?#{need}/, '')
77
+ add_need!("!#{need}")
78
+ end
79
+
80
+ def needs
81
+ if has_more_needs?
82
+ with_clause.split(' and ')
83
+ .map { |need| need.gsub!(/(needs\s)/, '') }
84
+ else
85
+ []
86
+ end
87
+ end
88
+
89
+ def next_tick
90
+ if has_more_needs?
91
+ next_need =
92
+ needs.find { |need| need !~ /^!/ } ||
93
+ (needs.find { |need| need =~ /^!/ }.gsub('!', '') rescue '')
94
+ "validate #{next_need}"
95
+ else
96
+ [verb, simple_subject].join(' ')
97
+ end
98
+ end
99
+
100
+ def new_request?
101
+ !!(with_clause.empty? && needs.empty?)
102
+ end
103
+
104
+ def prepositions
105
+ bare_patterns = [
106
+ /\sunder\s/, /\sfor\s/, /\sover\s/, /\swithin\s/, /\saliased\s/
107
+ ]
108
+ if block_given?
109
+ Regexp.union(bare_patterns.map { |pat| yield pat })
110
+ else
111
+ Regexp.union(bare_patterns)
112
+ end
113
+ end
114
+
115
+ def request?
116
+ !!(message =~ /^please/)
117
+ end
118
+
119
+ def simple_subject
120
+ subject.gsub(
121
+ /(.*?)#{prepositions { |prep| /#{prep.source + '.*'}/ }}/,
122
+ '\1'
123
+ )
124
+ end
125
+
126
+ def secondary_subject
127
+ subject.gsub(/.+for(.*)$/, '\1').strip
128
+ end
129
+
130
+ def sentiment
131
+ @sentiment || (
132
+ (message =~ /#{success_patterns}$/) ? :success : :fail
133
+ )
134
+ end
135
+
136
+ def subject(msg = message)
137
+ words = msg.split
138
+ if request?
139
+ lower_bound = 2
140
+ upper_bound = (words.reverse.index('with') || words.count)
141
+ words[lower_bound...upper_bound].join(' ')
142
+ else
143
+ words[0..-2].join(' ')
144
+ end
145
+ end
146
+
147
+ def success_patterns
148
+ Regexp.union([
149
+ /(connected)/, /(success)/, /(succeeded)/, /(successfull)/,
150
+ /(working)/, /(works)/, /(linked)/, /(done)/, /(skipped)/
151
+ ])
152
+ end
153
+
154
+ def ticked!(status)
155
+ words = message.split(' ')
156
+ words.shift # get rid of "please"
157
+ words.first.gsub!(/(\w+)e$/, "#{'\1'}ion") # change from imperative to declarative
158
+ words.insert(1, 'for') # finish changing to declarative sentence
159
+ words.push(status) # add the status of the task that ran to the end
160
+ @message = words.join(' ')
161
+ message
162
+ end
163
+
164
+ def verb
165
+ words = message.split(' ')
166
+ request? ? words[1] : words.last
167
+ end
168
+
169
+ def with_clause
170
+ return '' unless message =~ /with/
171
+ msg = message.gsub(/.+with\s(.+)$/, '\1')
172
+ if request?
173
+ msg
174
+ else
175
+ # pop the response status off, when dealing with a response
176
+ tmp = msg.split(' ')
177
+ tmp.pop
178
+ tmp.join(' ').strip
179
+ end
180
+ end
181
+ end
182
+ end
@@ -0,0 +1,195 @@
1
+ require 'rest-client'
2
+ require 'aws-sdk-s3'
3
+ require 'dotenv'
4
+ require 'json'
5
+ require 'uri'
6
+
7
+ module WGU
8
+ module ThycoticComms
9
+ def self.get(url, params = {})
10
+ res = nil
11
+ retry_count = 0
12
+ refresh_token = self.get_api_key
13
+ query_url = "#{url}?" + params.map { |k,v| "#{k}=#{v}&" }.join.gsub(/\&$/, '')
14
+ query_url = self.ss_url(query_url)
15
+ begin
16
+ RestClient.get(query_url,{ Authorization: "Bearer #{refresh_token}" })
17
+ res = RestClient.get(
18
+ query_url,
19
+ { Authorization: "Bearer #{refresh_token}" }
20
+ )
21
+ rescue RestClient::Unauthorized => e
22
+ retry_count += 1
23
+ refresh_token = self.update_tmp_pass!
24
+ retry unless retry_count > 1
25
+ raise e
26
+ end
27
+
28
+ JSON.parse(res.body)
29
+ end
30
+
31
+ def self.get_secret(query, folder_name)
32
+ secret_id_res = self.secret_lookup(query, folder_name)
33
+ secret_id_res.empty? ? { 'items' => [] } : self.secret_lookup(secret_id_res.first['id'])
34
+ end
35
+
36
+ def self.getter(term, body)
37
+ tupple = body['items'].find { |field| field['fieldName'][/^#{term}$/i] }
38
+ tupple['itemValue'] unless tupple.nil?
39
+ end
40
+
41
+ # find a good way to remove this hardcoding of 545 parent folder id
42
+ def self.folder_lookup(*args)
43
+ base_folder_id = 545
44
+ return base_folder_id if args.empty?
45
+ query = args[0] || base_folder_id
46
+ parent_folder_query = args[1]
47
+
48
+ params = if query.to_s[/^\d+$/]
49
+ ["api/v1/folders/#{query}"]
50
+ else
51
+ params_hash = { 'filter.searchText' => query }
52
+
53
+ unless parent_folder_query.nil?
54
+ params_hash['filter.parentFolder'] = parent_folder_query
55
+ end
56
+
57
+ ["api/v1/folders/lookup", params_hash]
58
+ end
59
+
60
+ self.get(*params)['records']
61
+ end
62
+
63
+ def self.secret_lookup(secret_query, folder_query = nil)
64
+ folder_id = if folder_query.to_s[/^\d+$/]
65
+ folder_query
66
+ else
67
+ res = self.folder_lookup(folder_query)
68
+ res.nil? ? self.folder_lookup : res.first['id']
69
+ end
70
+
71
+ secret_params = if secret_query.to_s[/^\d+$/]
72
+ ["api/v1/secrets/#{secret_query}"]
73
+ else
74
+ params_hash = if secret_query.kind_of?(String)
75
+ {
76
+ 'filter.folderId' => folder_id,
77
+ 'filter.searchText' => secret_query
78
+ }
79
+ else
80
+ { 'filter.parentFolderId' => folder_id }.merge(secret_query)
81
+ end
82
+
83
+ ['api/v1/secrets/lookup', params_hash]
84
+ end
85
+
86
+ result = self.get(*secret_params)
87
+ result.include?('records') ? result['records'] : result
88
+ end
89
+
90
+ private
91
+ def self.cache_client
92
+ @cache_client ||= Aws::S3::Client.new(
93
+ access_key_id: ENV['ACCESS_KEY_ID'],
94
+ secret_access_key: ENV['SECRET_ACCESS_KEY']
95
+ )
96
+ end
97
+
98
+ def self.update_tmp_pass!
99
+ cache_lock = nil
100
+ retry_count = 0
101
+ lock_file = 'locks/secret_store_refresh_token.lock'
102
+ key_file = 'secret_store_refresh_token'
103
+ bucket = Aws::S3::Bucket.new(
104
+ client: self.cache_client,
105
+ name: ENV['PPS_PASS_CACHE'],
106
+ versioning_configuration: {
107
+ mfa_delete: "Disabled",
108
+ status: "Enabled"
109
+ }
110
+ )
111
+ my_cache_lock = bucket.put_object(bucket: bucket.name, key: lock_file)
112
+ self.cache_client
113
+ .wait_until(:object_exists, bucket: bucket.name, key: lock_file)
114
+ first_version =
115
+ self.cache_client.get_object(bucket: bucket.name, key: lock_file)
116
+
117
+ if my_cache_lock.version_id.eql?(first_version.version_id)
118
+ key = self.get_new_key
119
+ self.cache_client.put_object({
120
+ body: key,
121
+ bucket: bucket.name,
122
+ key: key_file
123
+ })
124
+
125
+ bucket.put_object(key: key_file, body: key)
126
+ retry_count_for_suspend = 0
127
+ begin
128
+ bucket.versioning.suspend
129
+ rescue Exception => e
130
+ retry_count_for_suspend +=1
131
+ sleep 3
132
+ retry unless retry_count_for_suspend > 3
133
+ raise e
134
+ end
135
+ my_cache_lock.delete
136
+ bucket.object_versions(prefix: lock_file) do |version|
137
+ self.cache_client.delete_object(
138
+ bucket: bucket.name,
139
+ key: lock_file,
140
+ version_id: version.id
141
+ )
142
+ end
143
+ bucket.versioning.enable
144
+ key
145
+ else
146
+ should_stop = -> (retries) do
147
+ bucket.objects(prefix: lock_file).count.eql?(0) || retries > 20
148
+ end
149
+
150
+ until should_stop.call(retry_count)
151
+ retry_count += 1
152
+ sleep 3
153
+ end
154
+
155
+ self.cached_key
156
+ end
157
+ end
158
+
159
+ def self.get_api_key
160
+ self.cache_key || self.get_new_key
161
+ end
162
+
163
+ def self.cache_key
164
+ begin
165
+ self.cache_client.get_object(
166
+ bucket: ENV['PPS_PASS_CACHE'],
167
+ key: 'secret_store_refresh_token'
168
+ ).body.read
169
+ rescue Aws::S3::Errors::NoSuchKey => e
170
+ self.update_tmp_pass!
171
+ end
172
+ end
173
+
174
+ def self.get_new_key
175
+ res = RestClient.post(
176
+ self.ss_url(URI(ENV['SECRET_STORE_TOKEN'])),
177
+ {
178
+ 'username' => ENV['SECRET_STORE_USERNAME'],
179
+ 'password' => ENV['SECRET_STORE_PASSWORD'],
180
+ 'grant_type' => 'password'
181
+ },
182
+ {
183
+ content_type: "application/x-www-form-urlencoded",
184
+ 'cache-control' => 'no-cache'
185
+ }
186
+ )
187
+
188
+ JSON.parse(res.body)['access_token']
189
+ end
190
+
191
+ def self.ss_url(path = '')
192
+ URI(URI(ENV['SECRET_STORE_BASE_URL']) + URI(path)).to_s
193
+ end
194
+ end
195
+ end
@@ -0,0 +1,3 @@
1
+ module PPSCommons
2
+ VERSION = "0.1.2"
3
+ end
@@ -0,0 +1,10 @@
1
+ require 'pps_commons/commons'
2
+
3
+ module PPSCommons
4
+ include Commons
5
+ extend Commons::ClassMethods
6
+
7
+ def self.included(base)
8
+ base.send :include, Commons
9
+ end
10
+ end
@@ -0,0 +1,43 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "pps_commons/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "pps_commons"
8
+ spec.version = PPSCommons::VERSION
9
+ spec.authors = ["Adam Phillipps"]
10
+ spec.email = ["adam.phillipps@wgu.edu"]
11
+
12
+ spec.summary = %q{Some common functionality for the PPS project}
13
+ spec.description = %q{Some common functionality for the PPS project}
14
+ spec.homepage = "https://git.wgu.edu/projects/OPS/repos/pps_commons"
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+ # Our Nexus server is on a version that is too old, apparently...So this is
20
+ # going to be public until I get time to create a gem server in AWS.
21
+ # if spec.respond_to?(:metadata)
22
+ # spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
23
+ # else
24
+ # raise "RubyGems 2.0 or newer is required to protect against " \
25
+ # "public gem pushes."
26
+ # end
27
+
28
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
29
+ f.match(%r{^(test|spec|features)/})
30
+ end
31
+ spec.bindir = "exe"
32
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
33
+ spec.require_paths = ["lib"]
34
+
35
+ spec.add_dependency 'aws-sdk-s3', '~> 1'
36
+ spec.add_dependency 'chef-api', '~> 0.1'
37
+ spec.add_dependency 'rest-client', '~> 2.0'
38
+
39
+ spec.add_development_dependency 'byebug'
40
+ spec.add_development_dependency "bundler", "~> 1.16.a"
41
+ spec.add_development_dependency "rake", "~> 10.0"
42
+ spec.add_development_dependency "rspec", "~> 3.2"
43
+ end
metadata ADDED
@@ -0,0 +1,159 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: pps_commons
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.2
5
+ platform: ruby
6
+ authors:
7
+ - Adam Phillipps
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-11-23 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: aws-sdk-s3
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1'
27
+ - !ruby/object:Gem::Dependency
28
+ name: chef-api
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '0.1'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '0.1'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rest-client
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '2.0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '2.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: byebug
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: bundler
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: 1.16.a
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: 1.16.a
83
+ - !ruby/object:Gem::Dependency
84
+ name: rake
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '10.0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '10.0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: rspec
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '3.2'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '3.2'
111
+ description: Some common functionality for the PPS project
112
+ email:
113
+ - adam.phillipps@wgu.edu
114
+ executables: []
115
+ extensions: []
116
+ extra_rdoc_files: []
117
+ files:
118
+ - ".gitignore"
119
+ - ".rspec"
120
+ - CODE_OF_CONDUCT.md
121
+ - Gemfile
122
+ - LICENSE.txt
123
+ - README.md
124
+ - Rakefile
125
+ - bin/console
126
+ - bin/setup
127
+ - lib/pps_commons.rb
128
+ - lib/pps_commons/chef_comms.rb
129
+ - lib/pps_commons/commons.rb
130
+ - lib/pps_commons/delegation_agent.rb
131
+ - lib/pps_commons/sentence.rb
132
+ - lib/pps_commons/thycotic_comms.rb
133
+ - lib/pps_commons/version.rb
134
+ - pps_commons.gemspec
135
+ homepage: https://git.wgu.edu/projects/OPS/repos/pps_commons
136
+ licenses:
137
+ - MIT
138
+ metadata: {}
139
+ post_install_message:
140
+ rdoc_options: []
141
+ require_paths:
142
+ - lib
143
+ required_ruby_version: !ruby/object:Gem::Requirement
144
+ requirements:
145
+ - - ">="
146
+ - !ruby/object:Gem::Version
147
+ version: '0'
148
+ required_rubygems_version: !ruby/object:Gem::Requirement
149
+ requirements:
150
+ - - ">="
151
+ - !ruby/object:Gem::Version
152
+ version: '0'
153
+ requirements: []
154
+ rubyforge_project:
155
+ rubygems_version: 2.6.8
156
+ signing_key:
157
+ specification_version: 4
158
+ summary: Some common functionality for the PPS project
159
+ test_files: []