scenario_import.rb 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. require 'ostruct'
  2. # This is a helper class for managing Scenario imports, used by the ScenarioImportsController. This class behaves much
  3. # like a normal ActiveRecord object, with validations and callbacks. However, it is never persisted to the database.
  4. class ScenarioImport
  5. include ActiveModel::Model
  6. include ActiveModel::Callbacks
  7. include ActiveModel::Validations::Callbacks
  8. DANGEROUS_AGENT_TYPES = %w[Agents::ShellCommandAgent]
  9. URL_REGEX = /\Ahttps?:\/\//i
  10. attr_accessor :file, :url, :data, :do_import, :merges
  11. attr_reader :user
  12. before_validation :parse_file
  13. before_validation :fetch_url
  14. validate :validate_presence_of_file_url_or_data
  15. validates_format_of :url, :with => URL_REGEX, :allow_nil => true, :allow_blank => true, :message => "appears to be invalid"
  16. validate :validate_data
  17. validate :generate_diff
  18. def step_one?
  19. data.blank?
  20. end
  21. def step_two?
  22. data.present?
  23. end
  24. def set_user(user)
  25. @user = user
  26. end
  27. def existing_scenario
  28. @existing_scenario ||= user.scenarios.find_by(:guid => parsed_data["guid"])
  29. end
  30. def dangerous?
  31. (parsed_data['agents'] || []).any? { |agent| DANGEROUS_AGENT_TYPES.include?(agent['type']) }
  32. end
  33. def parsed_data
  34. @parsed_data ||= (data && JSON.parse(data) rescue {}) || {}
  35. end
  36. def agent_diffs
  37. @agent_diffs || generate_diff
  38. end
  39. def import_confirmed?
  40. do_import == "1"
  41. end
  42. def import(options = {})
  43. success = true
  44. guid = parsed_data['guid']
  45. description = parsed_data['description']
  46. name = parsed_data['name']
  47. links = parsed_data['links']
  48. control_links = parsed_data['control_links'] || []
  49. tag_fg_color = parsed_data['tag_fg_color']
  50. tag_bg_color = parsed_data['tag_bg_color']
  51. icon = parsed_data['icon']
  52. source_url = parsed_data['source_url'].presence || nil
  53. @scenario = user.scenarios.where(:guid => guid).first_or_initialize
  54. @scenario.update!(name: name, description: description,
  55. source_url: source_url, public: false,
  56. tag_fg_color: tag_fg_color,
  57. tag_bg_color: tag_bg_color,
  58. icon: icon)
  59. unless options[:skip_agents]
  60. created_agents = agent_diffs.map do |agent_diff|
  61. agent = agent_diff.agent || Agent.build_for_type("Agents::" + agent_diff.type.incoming, user)
  62. agent.guid = agent_diff.guid.incoming
  63. agent.attributes = { :name => agent_diff.name.updated,
  64. :disabled => agent_diff.disabled.updated, # == "true"
  65. :options => agent_diff.options.updated,
  66. :scenario_ids => [@scenario.id] }
  67. agent.schedule = agent_diff.schedule.updated if agent_diff.schedule.present?
  68. agent.keep_events_for = agent_diff.keep_events_for.updated if agent_diff.keep_events_for.present?
  69. agent.propagate_immediately = agent_diff.propagate_immediately.updated if agent_diff.propagate_immediately.present? # == "true"
  70. agent.service_id = agent_diff.service_id.updated if agent_diff.service_id.present?
  71. unless agent.save
  72. success = false
  73. errors.add(:base, "Errors when saving '#{agent_diff.name.incoming}': #{agent.errors.full_messages.to_sentence}")
  74. end
  75. agent
  76. end
  77. if success
  78. links.each do |link|
  79. receiver = created_agents[link['receiver']]
  80. source = created_agents[link['source']]
  81. receiver.sources << source unless receiver.sources.include?(source)
  82. end
  83. control_links.each do |control_link|
  84. controller = created_agents[control_link['controller']]
  85. control_target = created_agents[control_link['control_target']]
  86. controller.control_targets << control_target unless controller.control_targets.include?(control_target)
  87. end
  88. end
  89. end
  90. success
  91. end
  92. def scenario
  93. @scenario || @existing_scenario
  94. end
  95. protected
  96. def parse_file
  97. if data.blank? && file.present?
  98. self.data = file.read.force_encoding(Encoding::UTF_8)
  99. end
  100. end
  101. def fetch_url
  102. if data.blank? && url.present? && url =~ URL_REGEX
  103. self.data = Faraday.get(url).body
  104. end
  105. end
  106. def validate_data
  107. if data.present?
  108. @parsed_data = JSON.parse(data) rescue {}
  109. if (%w[name guid agents] - @parsed_data.keys).length > 0
  110. errors.add(:base, "The provided data does not appear to be a valid Scenario.")
  111. self.data = nil
  112. end
  113. else
  114. @parsed_data = nil
  115. end
  116. end
  117. def validate_presence_of_file_url_or_data
  118. unless file.present? || url.present? || data.present?
  119. errors.add(:base, "Please provide either a Scenario JSON File or a Public Scenario URL.")
  120. end
  121. end
  122. def generate_diff
  123. @agent_diffs = (parsed_data['agents'] || []).map.with_index do |agent_data, index|
  124. # AgentDiff is defined at the end of this file.
  125. agent_diff = AgentDiff.new(agent_data, parsed_data['schema_version'])
  126. if existing_scenario
  127. # If this Agent exists already, update the AgentDiff with the local version's information.
  128. agent_diff.diff_with! existing_scenario.agents.find_by(:guid => agent_data['guid'])
  129. begin
  130. # Update the AgentDiff with any hand-merged changes coming from the UI. This only happens when this
  131. # Agent already exists locally and has conflicting changes.
  132. agent_diff.update_from! merges[index.to_s] if merges
  133. rescue JSON::ParserError
  134. errors.add(:base, "Your updated options for '#{agent_data['name']}' were unparsable.")
  135. end
  136. end
  137. if agent_diff.requires_service? && merges.present? && merges[index.to_s].present? && merges[index.to_s]['service_id'].present?
  138. agent_diff.service_id = AgentDiff::FieldDiff.new(merges[index.to_s]['service_id'].to_i)
  139. end
  140. agent_diff
  141. end
  142. end
  143. # AgentDiff is a helper object that encapsulates an incoming Agent. All fields will be returned as an array
  144. # of either one or two values. The first value is the incoming value, the second is the existing value, if
  145. # it differs from the incoming value.
  146. class AgentDiff < OpenStruct
  147. class FieldDiff
  148. attr_accessor :incoming, :current, :updated
  149. def initialize(incoming)
  150. @incoming = incoming
  151. @updated = incoming
  152. end
  153. def set_current(current)
  154. @current = current
  155. @requires_merge = (incoming != current)
  156. end
  157. def requires_merge?
  158. @requires_merge
  159. end
  160. end
  161. def initialize(agent_data, schema_version)
  162. super()
  163. @schema_version = schema_version
  164. @requires_merge = false
  165. self.agent = nil
  166. store! agent_data
  167. end
  168. BASE_FIELDS = %w[name schedule keep_events_for propagate_immediately disabled guid]
  169. FIELDS_REQUIRING_TRANSLATION = %w[keep_events_for]
  170. def agent_exists?
  171. !!agent
  172. end
  173. def requires_merge?
  174. @requires_merge
  175. end
  176. def requires_service?
  177. !!agent_instance.try(:oauthable?)
  178. end
  179. def store!(agent_data)
  180. self.type = FieldDiff.new(agent_data["type"].split("::").pop)
  181. self.options = FieldDiff.new(agent_data['options'] || {})
  182. BASE_FIELDS.each do |option|
  183. if agent_data.has_key?(option)
  184. value = agent_data[option]
  185. value = send(:"translate_#{option}", value) if option.in?(FIELDS_REQUIRING_TRANSLATION)
  186. self[option] = FieldDiff.new(value)
  187. end
  188. end
  189. end
  190. def translate_keep_events_for(old_value)
  191. if schema_version < 1
  192. # Was stored in days, now is stored in seconds.
  193. old_value.to_i.days
  194. else
  195. old_value
  196. end
  197. end
  198. def schema_version
  199. (@schema_version || 0).to_i
  200. end
  201. def diff_with!(agent)
  202. return unless agent.present?
  203. self.agent = agent
  204. type.set_current(agent.short_type)
  205. options.set_current(agent.options || {})
  206. @requires_merge ||= type.requires_merge?
  207. @requires_merge ||= options.requires_merge?
  208. BASE_FIELDS.each do |field|
  209. next unless self[field].present?
  210. self[field].set_current(agent.send(field))
  211. @requires_merge ||= self[field].requires_merge?
  212. end
  213. end
  214. def update_from!(merges)
  215. each_field do |field, value, selection_options|
  216. value.updated = merges[field]
  217. end
  218. if options.requires_merge?
  219. options.updated = JSON.parse(merges['options'])
  220. end
  221. end
  222. def each_field
  223. boolean = [["True", "true"], ["False", "false"]]
  224. yield 'name', name if name.requires_merge?
  225. yield 'schedule', schedule, Agent::SCHEDULES.map {|s| [AgentHelper.builtin_schedule_name(s), s] } if self['schedule'].present? && schedule.requires_merge?
  226. yield 'keep_events_for', keep_events_for, Agent::EVENT_RETENTION_SCHEDULES if self['keep_events_for'].present? && keep_events_for.requires_merge?
  227. yield 'propagate_immediately', propagate_immediately, boolean if self['propagate_immediately'].present? && propagate_immediately.requires_merge?
  228. yield 'disabled', disabled, boolean if disabled.requires_merge?
  229. end
  230. def agent_instance
  231. "Agents::#{self.type.updated}".constantize.new
  232. end
  233. end
  234. end