contrast-agent 6.0.0 → 6.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (141) hide show
  1. checksums.yaml +4 -4
  2. data/ext/cs__assess_regexp/cs__assess_regexp.c +15 -2
  3. data/ext/cs__assess_regexp/cs__assess_regexp.h +2 -0
  4. data/ext/cs__assess_string/cs__assess_string.c +8 -0
  5. data/ext/cs__assess_test/cs__assess_test.h +9 -0
  6. data/ext/cs__assess_test/cs__assess_tests.c +22 -0
  7. data/ext/cs__assess_test/extconf.rb +5 -0
  8. data/ext/cs__common/cs__common.c +101 -0
  9. data/ext/cs__common/cs__common.h +29 -5
  10. data/ext/cs__contrast_patch/cs__contrast_patch.c +1 -1
  11. data/ext/cs__tests/cs__tests.c +12 -0
  12. data/ext/cs__tests/cs__tests.h +3 -0
  13. data/ext/cs__tests/extconf.rb +5 -0
  14. data/lib/contrast/agent/assess/contrast_object.rb +16 -16
  15. data/lib/contrast/agent/assess/events/source_event.rb +17 -19
  16. data/lib/contrast/agent/assess/policy/policy_scanner.rb +2 -16
  17. data/lib/contrast/agent/assess/policy/propagator/split.rb +15 -19
  18. data/lib/contrast/agent/assess/policy/trigger_method.rb +3 -11
  19. data/lib/contrast/agent/assess/rule/provider/hardcoded_value_rule.rb +7 -2
  20. data/lib/contrast/agent/assess/rule/response/base_rule.rb +11 -3
  21. data/lib/contrast/agent/assess/rule/response/cache_control_header_rule.rb +60 -36
  22. data/lib/contrast/agent/at_exit_hook.rb +1 -1
  23. data/lib/contrast/agent/inventory/database_config.rb +10 -3
  24. data/lib/contrast/agent/middleware.rb +3 -3
  25. data/lib/contrast/agent/patching/policy/after_load_patch.rb +0 -2
  26. data/lib/contrast/agent/patching/policy/patch.rb +13 -12
  27. data/lib/contrast/agent/patching/policy/patcher.rb +1 -1
  28. data/lib/contrast/agent/protect/input_analyzer/input_analyzer.rb +6 -2
  29. data/lib/contrast/agent/reporting/masker/masker.rb +8 -11
  30. data/lib/contrast/agent/reporting/masker/masker_utils.rb +8 -4
  31. data/lib/contrast/agent/reporting/reporter.rb +11 -16
  32. data/lib/contrast/agent/reporting/reporter_heartbeat.rb +49 -0
  33. data/lib/contrast/agent/reporting/reporting_events/agent_startup.rb +6 -2
  34. data/lib/contrast/agent/reporting/reporting_events/application_activity.rb +53 -0
  35. data/lib/contrast/agent/reporting/reporting_events/application_defend_activity.rb +48 -0
  36. data/lib/contrast/agent/reporting/reporting_events/application_defend_attack_activity.rb +64 -0
  37. data/lib/contrast/agent/reporting/reporting_events/application_defend_attack_sample.rb +70 -0
  38. data/lib/contrast/agent/reporting/reporting_events/application_defend_attack_sample_activity.rb +57 -0
  39. data/lib/contrast/agent/reporting/reporting_events/application_defend_attacker_activity.rb +56 -0
  40. data/lib/contrast/agent/reporting/reporting_events/application_inventory.rb +5 -1
  41. data/lib/contrast/agent/reporting/reporting_events/application_inventory_activity.rb +58 -0
  42. data/lib/contrast/agent/reporting/reporting_events/application_reporting_event.rb +27 -0
  43. data/lib/contrast/agent/reporting/reporting_events/application_startup.rb +20 -10
  44. data/lib/contrast/agent/reporting/reporting_events/application_update.rb +7 -12
  45. data/lib/contrast/agent/reporting/reporting_events/finding.rb +9 -3
  46. data/lib/contrast/agent/reporting/reporting_events/finding_event.rb +2 -4
  47. data/lib/contrast/agent/reporting/reporting_events/finding_event_object.rb +3 -3
  48. data/lib/contrast/agent/reporting/reporting_events/observed_library_usage.rb +6 -2
  49. data/lib/contrast/agent/reporting/reporting_events/observed_route.rb +7 -3
  50. data/lib/contrast/agent/reporting/reporting_events/poll.rb +6 -2
  51. data/lib/contrast/agent/reporting/reporting_events/preflight.rb +10 -8
  52. data/lib/contrast/agent/reporting/reporting_events/preflight_message.rb +6 -10
  53. data/lib/contrast/agent/reporting/reporting_events/server_activity.rb +12 -20
  54. data/lib/contrast/agent/reporting/reporting_events/server_reporting_event.rb +27 -0
  55. data/lib/contrast/agent/reporting/reporting_utilities/audit.rb +17 -27
  56. data/lib/contrast/agent/reporting/reporting_utilities/build_preflight.rb +38 -0
  57. data/lib/contrast/agent/reporting/reporting_utilities/dtm_message.rb +8 -0
  58. data/lib/contrast/agent/reporting/reporting_utilities/endpoints.rb +6 -0
  59. data/lib/contrast/agent/reporting/reporting_utilities/reporter_client.rb +9 -4
  60. data/lib/contrast/agent/reporting/reporting_utilities/reporter_client_utils.rb +54 -67
  61. data/lib/contrast/agent/reporting/reporting_utilities/response.rb +17 -7
  62. data/lib/contrast/agent/reporting/reporting_utilities/response_extractor.rb +8 -5
  63. data/lib/contrast/agent/reporting/reporting_utilities/response_handler.rb +10 -10
  64. data/lib/contrast/agent/reporting/reporting_utilities/response_handler_utils.rb +32 -17
  65. data/lib/contrast/agent/reporting/settings/protect.rb +1 -1
  66. data/lib/contrast/agent/reporting/settings/protect_server_feature.rb +1 -1
  67. data/lib/contrast/agent/request.rb +3 -3
  68. data/lib/contrast/agent/request_context_extend.rb +1 -1
  69. data/lib/contrast/agent/request_handler.rb +3 -3
  70. data/lib/contrast/agent/response.rb +2 -0
  71. data/lib/contrast/agent/service_heartbeat.rb +6 -48
  72. data/lib/contrast/agent/static_analysis.rb +1 -1
  73. data/lib/contrast/agent/telemetry/base.rb +151 -0
  74. data/lib/contrast/agent/telemetry/events/event.rb +35 -0
  75. data/lib/contrast/agent/telemetry/events/exceptions/telemetry_exception_base.rb +44 -36
  76. data/lib/contrast/agent/telemetry/events/exceptions/telemetry_exception_event.rb +29 -21
  77. data/lib/contrast/agent/telemetry/events/exceptions/telemetry_exception_message.rb +91 -73
  78. data/lib/contrast/agent/telemetry/events/exceptions/telemetry_exception_message_exception.rb +62 -44
  79. data/lib/contrast/agent/telemetry/events/exceptions/telemetry_exception_stack_frame.rb +50 -33
  80. data/lib/contrast/agent/telemetry/events/exceptions/telemetry_exceptions.rb +20 -0
  81. data/lib/contrast/agent/telemetry/events/exceptions/telemetry_exceptions_report.rb +32 -0
  82. data/lib/contrast/agent/telemetry/events/metric_event.rb +28 -0
  83. data/lib/contrast/agent/telemetry/events/startup_metrics_event.rb +123 -0
  84. data/lib/contrast/agent/thread_watcher.rb +52 -68
  85. data/lib/contrast/agent/version.rb +1 -1
  86. data/lib/contrast/agent/worker_thread.rb +8 -0
  87. data/lib/contrast/agent.rb +1 -3
  88. data/lib/contrast/api/communication/messaging_queue.rb +28 -11
  89. data/lib/contrast/api/communication/response_processor.rb +7 -10
  90. data/lib/contrast/api/communication/speedracer.rb +1 -1
  91. data/lib/contrast/api/decorators/activity.rb +33 -0
  92. data/lib/contrast/api/decorators/http_request.rb +1 -1
  93. data/lib/contrast/components/config.rb +13 -22
  94. data/lib/contrast/components/contrast_service.rb +9 -0
  95. data/lib/contrast/components/settings.rb +10 -0
  96. data/lib/contrast/config/agent_configuration.rb +21 -11
  97. data/lib/contrast/config/api_configuration.rb +12 -8
  98. data/lib/contrast/config/api_proxy_configuration.rb +7 -3
  99. data/lib/contrast/config/application_configuration.rb +15 -11
  100. data/lib/contrast/config/assess_configuration.rb +13 -9
  101. data/lib/contrast/config/assess_rules_configuration.rb +5 -1
  102. data/lib/contrast/config/base_configuration.rb +3 -35
  103. data/lib/contrast/config/certification_configuration.rb +9 -5
  104. data/lib/contrast/config/exception_configuration.rb +10 -7
  105. data/lib/contrast/config/heap_dump_configuration.rb +13 -9
  106. data/lib/contrast/config/inventory_configuration.rb +9 -6
  107. data/lib/contrast/config/logger_configuration.rb +9 -6
  108. data/lib/contrast/config/protect_configuration.rb +9 -6
  109. data/lib/contrast/config/protect_rule_configuration.rb +12 -8
  110. data/lib/contrast/config/protect_rules_configuration.rb +18 -17
  111. data/lib/contrast/config/request_audit_configuration.rb +10 -7
  112. data/lib/contrast/config/root_configuration.rb +28 -11
  113. data/lib/contrast/config/ruby_configuration.rb +14 -11
  114. data/lib/contrast/config/sampling_configuration.rb +11 -8
  115. data/lib/contrast/config/server_configuration.rb +13 -9
  116. data/lib/contrast/config/service_configuration.rb +14 -11
  117. data/lib/contrast/configuration.rb +19 -10
  118. data/lib/contrast/framework/rails/patch/support.rb +13 -45
  119. data/lib/contrast/logger/aliased_logging.rb +87 -0
  120. data/lib/contrast/logger/application.rb +0 -4
  121. data/lib/contrast/tasks/config.rb +22 -13
  122. data/lib/contrast/utils/class_util.rb +2 -6
  123. data/lib/contrast/utils/invalid_configuration_util.rb +1 -1
  124. data/lib/contrast/utils/log_utils.rb +2 -0
  125. data/lib/contrast/utils/middleware_utils.rb +1 -1
  126. data/lib/contrast/utils/object_share.rb +1 -1
  127. data/lib/contrast/utils/telemetry.rb +20 -2
  128. data/lib/contrast/utils/telemetry_client.rb +22 -10
  129. data/lib/contrast/utils/telemetry_hash.rb +41 -0
  130. data/lib/contrast/utils/telemetry_identifier.rb +16 -1
  131. data/lib/contrast.rb +9 -0
  132. data/ruby-agent.gemspec +1 -1
  133. data/service_executables/VERSION +1 -1
  134. data/service_executables/linux/contrast-service +0 -0
  135. data/service_executables/mac/contrast-service +0 -0
  136. metadata +39 -16
  137. data/lib/contrast/agent/telemetry/events/metric_telemetry_event.rb +0 -26
  138. data/lib/contrast/agent/telemetry/events/startup_metrics_telemetry_event.rb +0 -121
  139. data/lib/contrast/agent/telemetry/events/telemetry_event.rb +0 -33
  140. data/lib/contrast/agent/telemetry/telemetry.rb +0 -150
  141. data/lib/contrast/utils/exclude_key.rb +0 -20
@@ -78,9 +78,9 @@ module Contrast
78
78
  # in the standard format per RFC 2616
79
79
  # used for in observed routes message.
80
80
  return false unless response && (response_code = response&.code)
81
- return true if ANALYZE_WHEN.include? response_code
81
+ return true if ANALYZE_WHEN.include?(response_code)
82
82
 
83
- handle_error response if ERROR_CODES.value?(response_code)
83
+ handle_error(response) if ERROR_CODES.value?(response_code)
84
84
  # There was error, so analyze the Error and nothing more.
85
85
  false
86
86
  end
@@ -156,19 +156,14 @@ module Contrast
156
156
 
157
157
  response.application_settings.reactions.each do |reaction|
158
158
  # The enums are all uppercase, we need to downcase them before attempting to log.
159
- level = if reaction.level.nil?
160
- :error
161
- else
162
- reaction.level.downcase
163
- end
164
-
159
+ level = reaction.level.nil? ? :error : reaction.level.downcase
165
160
  logger.with_level(level, reaction.message) if reaction.message
166
161
 
167
162
  case reaction.operation
168
- when Contrast::Agent::Reporting::Settings::Reaction::OPERATIONS.second
163
+ when Contrast::Agent::Reporting::Settings::Reaction::OPERATIONS[1]
169
164
  # DISABLED
170
- Contrast::Agent::DisableReaction.run reaction, level
171
- when Contrast::Agent::Reporting::Settings::Reaction::OPERATIONS.first
165
+ Contrast::Agent::DisableReaction.run(reaction, level)
166
+ when Contrast::Agent::Reporting::Settings::Reaction::OPERATIONS[0]
172
167
  # NOOP
173
168
  else
174
169
  logger.warn('ReactionProcessor received a reaction with an unknown operation',
@@ -177,6 +172,24 @@ module Contrast
177
172
  end
178
173
  end
179
174
 
175
+ # This can't go in the Settings component because protect and assess depend on settings
176
+ # I don't think it should go into contrast_service because that only handles connection specific data.
177
+ #
178
+ # @param response [Contrast::Agent::Reporting::Response]
179
+ def update_ruleset response
180
+ logger.info('Updating features from TeamServer')
181
+ return unless response&.server_features || response&.application_settings
182
+ return unless ::Contrast::AGENT.enabled?
183
+
184
+ logger.trace_with_time('Rebuilding rule modes from TeamServer') do
185
+ ::Contrast::SETTINGS.build_protect_rules if ::Contrast::PROTECT.enabled?
186
+ ::Contrast::AGENT.reset_ruleset
187
+ logger.info('Current rule settings:')
188
+ ::Contrast::PROTECT.rules.each { |k, v| logger.info('Protect Rule mode set', rule: k, mode: v.mode) }
189
+ logger.info('Disabled Assess Rules', rules: ::Contrast::ASSESS.disabled_rules)
190
+ end
191
+ end
192
+
180
193
  # Converts response from Net to Reporting Response object
181
194
  #
182
195
  # @param response [Net::HTTP::Response, nil]
@@ -192,12 +205,14 @@ module Contrast
192
205
  # check if response contains application settings or Feature settings
193
206
  if response_data[:settings]
194
207
  # the response contains ApplicationSettings
195
- logger.trace('Agent: Received updated application settings')
196
- build_application_settings response_data
208
+ app_settings = build_application_settings(response_data)
209
+ logger.trace('Agent: Received updated application settings', raw: response_data, processed: app_settings)
210
+ app_settings
197
211
  else
198
212
  # the response contains FeatureSettings
199
- logger.trace('Agent: Received updated server features')
200
- build_feature_settings response_data
213
+ server_features = build_feature_settings(response_data)
214
+ logger.trace('Agent: Received updated application settings', raw: response_data, processed: server_features)
215
+ server_features
201
216
  end
202
217
  rescue StandardError => e
203
218
  logger.error('Unable to convert response', e)
@@ -207,7 +222,7 @@ module Contrast
207
222
  # @param response_data [Hash]
208
223
  # @return res [Contrast::Agent::Reporting::Response]
209
224
  def build_application_settings response_data
210
- res = Contrast::Agent::Reporting::Response.new
225
+ res = Contrast::Agent::Reporting::Response.application_response
211
226
  extract_assess response_data, res
212
227
  extract_protect response_data, res
213
228
  extract_exclusions response_data, res
@@ -219,7 +234,7 @@ module Contrast
219
234
  # @param response_data [Hash]
220
235
  # @return res [Contrast::Agent::Reporting::Response]
221
236
  def build_feature_settings response_data
222
- res = Contrast::Agent::Reporting::Response.new
237
+ res = Contrast::Agent::Reporting::Response.server_response
223
238
  extract_assess_server_features response_data, res
224
239
  extract_protect_server_features response_data, res
225
240
  extract_protect_lists response_data, res
@@ -73,7 +73,7 @@ module Contrast
73
73
  #
74
74
  # @return rules [Hash<RULE_ID => MODE>, nil] Hash with rule_id as key and mode as value
75
75
  def protection_rules_to_settings_hash
76
- return if protection_rules.empty?
76
+ return {} if protection_rules.empty?
77
77
 
78
78
  modes_by_id = {}
79
79
  protection_rules.each do |rule|
@@ -23,7 +23,7 @@ module Contrast
23
23
  # @param enabled [Boolean]
24
24
  # @return enabled [Boolean]
25
25
  def enabled= enabled
26
- @_enabled = enabled if !!enabled == enabled
26
+ @_enabled = enabled
27
27
  end
28
28
 
29
29
  # Indicate if the bot protection feature set is enabled for this server or not.
@@ -39,7 +39,7 @@ module Contrast
39
39
  attr_accessor :route, :observed_route, :new_observed_route
40
40
 
41
41
  # Delegate calls to the following methods to the attribute @rack_request
42
- def_delegators :@rack_request, :base_url, :content_type, :cookies, :env, :ip, :path, :port, :query_string,
42
+ def_delegators :@rack_request, :base_url, :cookies, :env, :ip, :media_type, :path, :port, :query_string,
43
43
  :request_method, :scheme, :url, :user_agent
44
44
 
45
45
  # Initialize new Contrast Request
@@ -86,9 +86,9 @@ module Contrast
86
86
  #
87
87
  # @return type [Symbol<:XML, :JSON, :NORMAL>]
88
88
  def document_type
89
- @_document_type ||= if /xml/i.match?(content_type) || body&.start_with?('<?xml')
89
+ @_document_type ||= if /xml/i.match?(media_type) || body&.start_with?('<?xml')
90
90
  :XML
91
- elsif /json/i.match?(content_type) || body&.match?(/\s*[{\[]/)
91
+ elsif /json/i.match?(media_type) || body&.match?(/\s*[{\[]/)
92
92
  :JSON
93
93
  else
94
94
  :NORMAL
@@ -76,7 +76,7 @@ module Contrast
76
76
  return false unless ::Contrast::PROTECT.enabled?
77
77
  return false if @do_not_track
78
78
 
79
- service_response = Contrast::Agent.messaging_queue.send_event_immediately(@activity.http_request)
79
+ service_response = Contrast::Agent&.messaging_queue&.send_event_immediately(@activity.http_request)
80
80
  return false unless service_response
81
81
 
82
82
  handle_protect_state(service_response)
@@ -47,8 +47,7 @@ module Contrast
47
47
  # This method is used to send our JSON messages directly to TeamServer at the end of each request. As we move
48
48
  # more endpoints over, this method will take the messages originally sent by #send_actiivty_messages. At the end,
49
49
  # that method should be removed.
50
- # TODO: RUBY-1358
51
- def report_activity
50
+ def report_activity # rubocop:disable Metrics/AbcSize
52
51
  return unless Contrast::Agent::Reporter.enabled?
53
52
 
54
53
  reporter = Contrast::Agent.reporter
@@ -61,7 +60,8 @@ module Contrast
61
60
  [
62
61
  context.new_observed_route,
63
62
  Contrast::Agent::Reporting::DtmMessage.dtm_to_event(context.server_activity),
64
- Contrast::Agent::Reporting::DtmMessage.dtm_to_event(context.activity.library_usages)
63
+ Contrast::Agent::Reporting::DtmMessage.dtm_to_event(context.activity.library_usages),
64
+ Contrast::Agent::Reporting::DtmMessage.dtm_to_event(context.activity)
65
65
  ].each do |event|
66
66
  reporter.send_event(event)
67
67
  rescue StandardError => e
@@ -22,6 +22,8 @@ module Contrast
22
22
 
23
23
  extend Forwardable
24
24
 
25
+ # @return [Array, Rack::Response] The Rack Response passed by the application & middleware. It can be an Array
26
+ # in format [response_code, header_hash, response_body] or an instance of Rack::Response
25
27
  attr_reader :rack_response
26
28
 
27
29
  def initialize rack_response
@@ -7,71 +7,29 @@ require 'contrast/agent/reporting/report'
7
7
 
8
8
  module Contrast
9
9
  module Agent
10
- # The ServiceHeartbeat functions to keep the Contrast Service alive and
11
- # ensure that it maintains this Agent's ApplicationContext.
10
+ # The ServiceHeartbeat functions to keep the Contrast Service alive and ensure that it maintains this Agent's
11
+ # ApplicationContext.
12
12
  class ServiceHeartbeat < WorkerThread
13
13
  include Contrast::Components::Logger::InstanceMethods
14
14
 
15
15
  # Spec recommends 30 seconds, we're going with 15.
16
16
  REFRESH_INTERVAL_SEC = 15
17
17
 
18
- # check if we can report to TS
19
- #
20
- # @return[Boolean] true if bypass is enabled, or false if bypass disabled
21
- def enabled?
22
- @_enabled = Contrast::CONTRAST_SERVICE.use_agent_communication? if @_enabled.nil?
23
- @_enabled
24
- end
25
-
26
- def client
27
- @_client ||= Contrast::Agent::Reporting::ReporterClient.new
28
- end
29
-
30
- def connection
31
- @_connection ||= client.initialize_connection
32
- end
33
-
34
18
  def start_thread!
19
+ return if ::Contrast::CONTRAST_SERVICE.unnecessary?
35
20
  return if running?
36
21
 
37
- report_from_reporter = check_report_provider
38
-
39
22
  @_thread = Contrast::Agent::Thread.new do
40
23
  logger.info('Starting heartbeat thread.')
41
24
  loop do
42
- if report_from_reporter
43
- client.send_event(poll_message, connection)
44
- else
45
- Contrast::Agent.messaging_queue.send_event_eventually(poll_message)
46
- end
47
-
48
- sleep REFRESH_INTERVAL_SEC
25
+ Contrast::Agent.messaging_queue.send_event_eventually(poll_message)
26
+ sleep(REFRESH_INTERVAL_SEC)
49
27
  end
50
28
  end
51
29
  end
52
30
 
53
31
  def poll_message
54
- @_poll_message ||= if enabled? && client
55
- Contrast::Agent::Reporting::Poll.new
56
- else
57
- Contrast::Api::Dtm::Poll.new
58
- end
59
- end
60
-
61
- def check_report_provider
62
- return false unless enabled?
63
- return false unless client && connection
64
-
65
- client.startup!(connection)
66
- true
67
- end
68
-
69
- def send_event provider
70
- if provider
71
- client.send_event(poll_message, connection)
72
- return
73
- end
74
- Contrast::Agent.messaging_queue.send_event_eventually(poll_message)
32
+ @_poll_message ||= Contrast::Api::Dtm::Poll.new
75
33
  end
76
34
  end
77
35
  end
@@ -40,7 +40,7 @@ module Contrast
40
40
  inventory_report = Contrast::Agent::Reporting::ApplicationInventory.convert(app_update_msg)
41
41
  Contrast::Agent.reporter.send_event(inventory_report)
42
42
  else
43
- Contrast::Agent.messaging_queue.send_event_eventually(app_update_msg)
43
+ Contrast::Agent.messaging_queue.send_event_eventually(app_update_msg, force: true)
44
44
  end
45
45
  end
46
46
 
@@ -0,0 +1,151 @@
1
+ # Copyright (c) 2022 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
2
+ # frozen_string_literal: true
3
+
4
+ require 'contrast/config/env_variables'
5
+ require 'contrast/components/logger'
6
+ require 'contrast/utils/telemetry_client'
7
+ require 'contrast/agent/worker_thread'
8
+ require 'contrast/utils/telemetry'
9
+ require 'contrast/agent/telemetry/events/exceptions/telemetry_exceptions'
10
+
11
+ module Contrast
12
+ module Agent
13
+ module Telemetry
14
+ # This class will initialize and hold everything needed for the telemetry
15
+ class Base < WorkerThread
16
+ include Contrast::Components::Logger::InstanceMethods
17
+ # this is where we will send the data from the agents
18
+ URL = 'https://telemetry.ruby.contrastsecurity.com/'
19
+ # Suggested timeout after each send is to be 3 hours (10800 seconds)
20
+ SUGGESTED_TIMEOUT = 10_800
21
+
22
+ class << self
23
+ include Contrast::Components::Logger::InstanceMethods
24
+ include Contrast::Config::EnvVariables
25
+
26
+ def application_id
27
+ Contrast::Utils::Telemetry::Identifier.application_id
28
+ end
29
+
30
+ def instance_id
31
+ Contrast::Utils::Telemetry::Identifier.instance_id
32
+ end
33
+
34
+ def enabled?
35
+ @_enabled = telemetry_enabled? if @_enabled.nil?
36
+ @_enabled
37
+ end
38
+
39
+ private
40
+
41
+ def telemetry_enabled?
42
+ opt_out_telemetry = return_value(:telemetry_opt_outs).to_s
43
+ return false if opt_out_telemetry.casecmp?('true') || opt_out_telemetry == '1'
44
+
45
+ # In case of connection error, do not create the background thread or queue,
46
+ # as if the opt-out env var was set
47
+ @_client = Contrast::Utils::TelemetryClient.new
48
+ ip_opt_out_telemetry = @_client.initialize_connection(URL)
49
+ if ip_opt_out_telemetry.nil?
50
+ logger.warn("Connection was not established properly!!! \n Telemetry reporting will be disabled!")
51
+ return false
52
+ end
53
+
54
+ true
55
+ end
56
+ end
57
+
58
+ def client
59
+ @_client ||= Contrast::Utils::TelemetryClient.new
60
+ end
61
+
62
+ def connection
63
+ @_connection ||= client.initialize_connection(URL)
64
+ end
65
+
66
+ def error_messages
67
+ @_error_messages ||= []
68
+ end
69
+
70
+ def attempt_to_start?
71
+ unless cs__class.enabled?
72
+ logger.warn('Telemetry service is disabled!')
73
+ return false
74
+ end
75
+
76
+ logger.debug('Attempting to start telemetry thread') unless running?
77
+ true
78
+ end
79
+
80
+ def start_thread!
81
+ return if running?
82
+
83
+ # It is recommended that implementations send a single payload of
84
+ # general metrics every 3 hours, starting from implementation startup.
85
+ @_thread = Contrast::Agent::Thread.new do
86
+ logger.debug('Starting background telemetry thread.')
87
+ loop do
88
+ next unless client && connection
89
+
90
+ Contrast::Agent::Telemetry::TelemetryExceptionReport.push_exceptions
91
+ until queue.empty?
92
+ event = queue.pop
93
+ begin
94
+ logger.debug('This is the current processed event', event)
95
+ sleep_time = request_with_response event
96
+ if sleep_time
97
+ sleep(sleep_time)
98
+ logger.debug('Retrying to process event', event)
99
+ retry_sleep_time = request_with_response event
100
+ sleep(retry_sleep_time) unless retry_sleep_time.nil?
101
+ end
102
+ rescue StandardError => e
103
+ logger.error('Could not send message to service from telemetry queue.', e)
104
+ stop!
105
+ end
106
+ end
107
+ sleep(SUGGESTED_TIMEOUT)
108
+ end
109
+ end
110
+ end
111
+
112
+ def send_event event
113
+ if ::Contrast::AGENT.disabled?
114
+ logger.warn('Attempted to queue event with Agent disabled', caller: caller, event: event)
115
+ return
116
+ end
117
+
118
+ return unless cs__class.enabled?
119
+
120
+ logger.debug('Enqueued event for sending', event_type: event.cs__class)
121
+ queue << event if event
122
+ end
123
+
124
+ def delete_queue!
125
+ @_queue&.clear
126
+ @_queue&.close
127
+ @_queue = nil
128
+ end
129
+
130
+ def stop!
131
+ return unless running?
132
+
133
+ @_enabled = false
134
+ delete_queue!
135
+ super
136
+ end
137
+
138
+ def request_with_response event
139
+ res = client.send_request event, connection
140
+ client.handle_response res
141
+ end
142
+
143
+ private
144
+
145
+ def queue
146
+ @_queue ||= Queue.new
147
+ end
148
+ end
149
+ end
150
+ end
151
+ end
@@ -0,0 +1,35 @@
1
+ # Copyright (c) 2022 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
2
+ # frozen_string_literal: true
3
+
4
+ require 'contrast/utils/metrics_hash'
5
+
6
+ module Contrast
7
+ module Agent
8
+ module Telemetry
9
+ # This class will hold the basic information for a Telemetry Event
10
+ class Event
11
+ include Contrast::Utils
12
+
13
+ attr_reader :tags
14
+
15
+ def initialize
16
+ @tags = MetricsHash.new(String)
17
+ @timestamp = Time.now.iso8601
18
+ end
19
+
20
+ def path
21
+ ''
22
+ end
23
+
24
+ def to_hash **_args
25
+ {
26
+ tags: @tags,
27
+ timestamp: @timestamp,
28
+ instance: Contrast::Agent::Telemetry::Base.instance_id,
29
+ application: Contrast::Agent::Telemetry::Base.application_id
30
+ }
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
@@ -3,48 +3,56 @@
3
3
 
4
4
  module Contrast
5
5
  module Agent
6
- # This class will hold the all the mutual information for the Telemetry Exception
7
- class TelemetryExceptionBase
8
- def to_controlled_hash; end
6
+ module Telemetry
7
+ module TelemetryException
8
+ # This class will hold the all the mutual information for the Telemetry Exception
9
+ class Base
10
+ def to_controlled_hash; end
9
11
 
10
- protected
12
+ protected
11
13
 
12
- # Validate required and option fields
13
- #
14
- # @param validations [Hash] Validation hash to use
15
- # @return [nil]
16
- def validate validations
17
- validations.each do |k, v|
18
- next if v[:required] == false
14
+ # Validate required and option fields
15
+ #
16
+ # @param validations [Hash] Validation hash to use
17
+ # @return [nil]
18
+ def validate validations
19
+ validations.each do |k, v|
20
+ next if v[:required] == false
19
21
 
20
- validate_field validations[k], k
21
- end
22
- nil
23
- end
22
+ validate_field(validations[k], k)
23
+ end
24
+ nil
25
+ end
24
26
 
25
- # This method will validate every single field passed from validate
26
- #
27
- # @param validation_pair [Hash] Validation hash to use
28
- # @param key[String] The key to check in VALIDATIONS
29
- def validate_field validation_pair, key
30
- value_to_validate = send(key.to_sym)
31
- validate_class value_to_validate, validation_pair[:class], key if validation_pair.key?(:class)
32
- value_length = value_to_validate.cs__is_a?(String) ? value_to_validate.length : value_to_validate.entries.length
33
- unless validation_pair[:range].include?(value_length)
34
- raise ArgumentError, "The provided value for #{ key } is invalid"
35
- end
27
+ # This method will validate every single field passed from validate
28
+ #
29
+ # @param validation_pair [Hash] Validation hash to use
30
+ # @param key[String] The key to check in VALIDATIONS
31
+ def validate_field validation_pair, key
32
+ value_to_validate = send(key.to_sym)
33
+ validate_class(value_to_validate, validation_pair[:class], key) if validation_pair.key?(:class)
34
+ value_length = if value_to_validate.cs__is_a?(String) || value_to_validate.cs__is_a?(Array)
35
+ value_to_validate.length
36
+ else
37
+ value_to_validate.entries.length
38
+ end
39
+ unless validation_pair[:range].include?(value_length)
40
+ raise ArgumentError, "The provided value for #{ key } is invalid: #{ value_to_validate }"
41
+ end
36
42
 
37
- nil
38
- end
43
+ nil
44
+ end
39
45
 
40
- # With the all nested classes, we still need to double check if everything passed along the way
41
- # is right
42
- # @param message [Object] The message we want to check the class of
43
- # @param klass [Class] The klass we want to check the message with
44
- # @param field [Object] The field with the error
45
- def validate_class message, klass, field
46
- message = message[0] if message.cs__is_a?(Array)
47
- raise ArgumentError, "The provided value for #{ field } is invalid" unless message.cs__is_a? klass
46
+ # With the all nested classes, we still need to double check if everything passed along the way
47
+ # is right
48
+ # @param message [Object] The message we want to check the class of
49
+ # @param klass [Class] The klass we want to check the message with
50
+ # @param field [Object] The field with the error
51
+ def validate_class message, klass, field
52
+ message = message[0] if message.cs__is_a?(Array)
53
+ raise ArgumentError, "The provided value for #{ field } is of wrong class" unless message.cs__is_a? klass
54
+ end
55
+ end
48
56
  end
49
57
  end
50
58
  end
@@ -6,30 +6,38 @@ require_relative 'telemetry_exception_message'
6
6
 
7
7
  module Contrast
8
8
  module Agent
9
- # This class will hold the basic information for a Parent Telemetry Exception Event
10
- class TelemetryExceptionEvent < Contrast::Agent::TelemetryExceptionBase
11
- # Array of Telemetry Exclusions
12
- # @return [Array<Contrast::Agent::TelemetryExceptionMessage>]
13
- attr_reader :exclusions
9
+ module Telemetry
10
+ module TelemetryException
11
+ # This class will hold the basic information for a Parent Telemetry Exception Event
12
+ class Event < Contrast::Agent::Telemetry::TelemetryException::Base
13
+ # Array of Telemetry Exceptions
14
+ # @return [Array<Contrast::Agent::Telemetry::TelemetryException::Message>]
15
+ attr_reader :exceptions
14
16
 
15
- # Initialization of the Parent Event requires us to require the exception
16
- # to be created
17
- #
18
- # @param message [Contrast::Agent::TelemetryExceptionMessage]
19
- def initialize message
20
- super()
21
- validate_class message, Contrast::Agent::TelemetryExceptionMessage, 'exception_message'
22
- @exclusions = Array.new(1, message)
23
- end
17
+ # Initialization of the Parent Event requires us to require the exception
18
+ # to be created
19
+ #
20
+ # @param message [Contrast::Agent::Telemetry::TelemetryException::Message]
21
+ def initialize message
22
+ super()
23
+ validate_class(message, Contrast::Agent::Telemetry::TelemetryException::Message, 'exception_message')
24
+ @exceptions = Array.new(1, message)
25
+ end
24
26
 
25
- # @param message [Contrast::Agent::TelemetryExceptionMessage]
26
- def push message
27
- validate_class message, Contrast::Agent::TelemetryExceptionMessage, 'exception_message'
28
- @exclusions << message
29
- end
27
+ # @param message [Contrast::Agent::Telemetry::TelemetryException::Message]
28
+ def push message
29
+ validate_class(message, Contrast::Agent::Telemetry::TelemetryException::Message, 'exception_message')
30
+ @exceptions << message
31
+ end
32
+
33
+ def self.path
34
+ '/ruby/runtime'
35
+ end
30
36
 
31
- def to_controlled_hash
32
- exclusions.map(&:to_controlled_hash)
37
+ def to_controlled_hash
38
+ exceptions.map(&:to_controlled_hash)
39
+ end
40
+ end
33
41
  end
34
42
  end
35
43
  end