scenario_import.rb 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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 should_import?
  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. source_url = parsed_data['source_url'].presence || nil
  52. @scenario = user.scenarios.where(:guid => guid).first_or_initialize
  53. @scenario.update_attributes!(:name => name, :description => description,
  54. :source_url => source_url, :public => false,
  55. :tag_fg_color => tag_fg_color,
  56. :tag_bg_color => tag_bg_color)
  57. unless options[:skip_agents]
  58. created_agents = agent_diffs.map do |agent_diff|
  59. agent = agent_diff.agent || Agent.build_for_type("Agents::" + agent_diff.type.incoming, user)
  60. agent.guid = agent_diff.guid.incoming
  61. agent.attributes = { :name => agent_diff.name.updated,
  62. :disabled => agent_diff.disabled.updated, # == "true"
  63. :options => agent_diff.options.updated,
  64. :scenario_ids => [@scenario.id] }
  65. agent.schedule = agent_diff.schedule.updated if agent_diff.schedule.present?
  66. agent.keep_events_for = agent_diff.keep_events_for.updated if agent_diff.keep_events_for.present?
  67. agent.propagate_immediately = agent_diff.propagate_immediately.updated if agent_diff.propagate_immediately.present? # == "true"
  68. agent.service_id = agent_diff.service_id.updated if agent_diff.service_id.present?
  69. unless agent.save
  70. success = false
  71. errors.add(:base, "Errors when saving '#{agent_diff.name.incoming}': #{agent.errors.full_messages.to_sentence}")
  72. end
  73. agent
  74. end
  75. if success
  76. links.each do |link|
  77. receiver = created_agents[link['receiver']]
  78. source = created_agents[link['source']]
  79. receiver.sources << source unless receiver.sources.include?(source)
  80. end
  81. control_links.each do |control_link|
  82. controller = created_agents[control_link['controller']]
  83. control_target = created_agents[control_link['control_target']]
  84. controller.control_targets << control_target unless controller.control_targets.include?(control_target)
  85. end
  86. end
  87. end
  88. success
  89. end
  90. def scenario
  91. @scenario || @existing_scenario
  92. end
  93. def will_request_local?(url_root)
  94. data.blank? && file.blank? && url.present? && url.starts_with?(url_root)
  95. end
  96. protected
  97. def parse_file
  98. if data.blank? && file.present?
  99. self.data = file.read.force_encoding(Encoding::UTF_8)
  100. end
  101. end
  102. def fetch_url
  103. if data.blank? && url.present? && url =~ URL_REGEX
  104. self.data = Faraday.get(url).body
  105. end
  106. end
  107. def validate_data
  108. if data.present?
  109. @parsed_data = JSON.parse(data) rescue {}
  110. if (%w[name guid agents] - @parsed_data.keys).length > 0
  111. errors.add(:base, "The provided data does not appear to be a valid Scenario.")
  112. self.data = nil
  113. end
  114. else
  115. @parsed_data = nil
  116. end
  117. end
  118. def validate_presence_of_file_url_or_data
  119. unless file.present? || url.present? || data.present?
  120. errors.add(:base, "Please provide either a Scenario JSON File or a Public Scenario URL.")
  121. end
  122. end
  123. def generate_diff
  124. @agent_diffs = (parsed_data['agents'] || []).map.with_index do |agent_data, index|
  125. # AgentDiff is defined at the end of this file.
  126. agent_diff = AgentDiff.new(agent_data, parsed_data['schema_version'])
  127. if existing_scenario
  128. # If this Agent exists already, update the AgentDiff with the local version's information.
  129. agent_diff.diff_with! existing_scenario.agents.find_by(:guid => agent_data['guid'])
  130. begin
  131. # Update the AgentDiff with any hand-merged changes coming from the UI. This only happens when this
  132. # Agent already exists locally and has conflicting changes.
  133. agent_diff.update_from! merges[index.to_s] if merges
  134. rescue JSON::ParserError
  135. errors.add(:base, "Your updated options for '#{agent_data['name']}' were unparsable.")
  136. end
  137. end
  138. if agent_diff.requires_service? && merges.present? && merges[index.to_s].present? && merges[index.to_s]['service_id'].present?
  139. agent_diff.service_id = AgentDiff::FieldDiff.new(merges[index.to_s]['service_id'].to_i)
  140. end
  141. agent_diff
  142. end
  143. end
  144. # AgentDiff is a helper object that encapsulates an incoming Agent. All fields will be returned as an array
  145. # of either one or two values. The first value is the incoming value, the second is the existing value, if
  146. # it differs from the incoming value.
  147. class AgentDiff < OpenStruct
  148. class FieldDiff
  149. attr_accessor :incoming, :current, :updated
  150. def initialize(incoming)
  151. @incoming = incoming
  152. @updated = incoming
  153. end
  154. def set_current(current)
  155. @current = current
  156. @requires_merge = (incoming != current)
  157. end
  158. def requires_merge?
  159. @requires_merge
  160. end
  161. end
  162. def initialize(agent_data, schema_version)
  163. super()
  164. @schema_version = schema_version
  165. @requires_merge = false
  166. self.agent = nil
  167. store! agent_data
  168. end
  169. BASE_FIELDS = %w[name schedule keep_events_for propagate_immediately disabled guid]
  170. FIELDS_REQUIRING_TRANSLATION = %w[keep_events_for]
  171. def agent_exists?
  172. !!agent
  173. end
  174. def requires_merge?
  175. @requires_merge
  176. end
  177. def requires_service?
  178. !!agent_instance.try(:oauthable?)
  179. end
  180. def store!(agent_data)
  181. self.type = FieldDiff.new(agent_data["type"].split("::").pop)
  182. self.options = FieldDiff.new(agent_data['options'] || {})
  183. BASE_FIELDS.each do |option|
  184. if agent_data.has_key?(option)
  185. value = agent_data[option]
  186. value = send(:"translate_#{option}", value) if option.in?(FIELDS_REQUIRING_TRANSLATION)
  187. self[option] = FieldDiff.new(value)
  188. end
  189. end
  190. end
  191. def translate_keep_events_for(old_value)
  192. if schema_version < 1
  193. # Was stored in days, now is stored in seconds.
  194. old_value.to_i.days
  195. else
  196. old_value
  197. end
  198. end
  199. def schema_version
  200. (@schema_version || 0).to_i
  201. end
  202. def diff_with!(agent)
  203. return unless agent.present?
  204. self.agent = agent
  205. type.set_current(agent.short_type)
  206. options.set_current(agent.options || {})
  207. @requires_merge ||= type.requires_merge?
  208. @requires_merge ||= options.requires_merge?
  209. BASE_FIELDS.each do |field|
  210. next unless self[field].present?
  211. self[field].set_current(agent.send(field))
  212. @requires_merge ||= self[field].requires_merge?
  213. end
  214. end
  215. def update_from!(merges)
  216. each_field do |field, value, selection_options|
  217. value.updated = merges[field]
  218. end
  219. if options.requires_merge?
  220. options.updated = JSON.parse(merges['options'])
  221. end
  222. end
  223. def each_field
  224. boolean = [["True", "true"], ["False", "false"]]
  225. yield 'name', name if name.requires_merge?
  226. yield 'schedule', schedule, Agent::SCHEDULES.map {|s| [s.humanize.titleize, s] } if self['schedule'].present? && schedule.requires_merge?
  227. yield 'keep_events_for', keep_events_for, Agent::EVENT_RETENTION_SCHEDULES if self['keep_events_for'].present? && keep_events_for.requires_merge?
  228. yield 'propagate_immediately', propagate_immediately, boolean if self['propagate_immediately'].present? && propagate_immediately.requires_merge?
  229. yield 'disabled', disabled, boolean if disabled.requires_merge?
  230. end
  231. def agent_instance
  232. "Agents::#{self.type.updated}".constantize.new
  233. end
  234. end
  235. end