webhook_agent.rb 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. module Agents
  2. class WebhookAgent < Agent
  3. include EventHeadersConcern
  4. include WebRequestConcern # to make reCAPTCHA verification requests
  5. cannot_be_scheduled!
  6. cannot_receive_events!
  7. description do <<-MD
  8. The Webhook Agent will create events by receiving webhooks from any source. In order to create events with this agent, make a POST request to:
  9. ```
  10. https://#{ENV['DOMAIN']}/users/#{user.id}/web_requests/#{id || ':id'}/#{options['secret'] || ':secret'}
  11. ```
  12. #{'The placeholder symbols above will be replaced by their values once the agent is saved.' unless id}
  13. Options:
  14. * `secret` - A token that the host will provide for authentication.
  15. * `expected_receive_period_in_days` - How often you expect to receive
  16. events this way. Used to determine if the agent is working.
  17. * `payload_path` - JSONPath of the attribute in the POST body to be
  18. used as the Event payload. Set to `.` to return the entire message.
  19. If `payload_path` points to an array, Events will be created for each element.
  20. * `event_headers` - Comma-separated list of HTTP headers your agent will include in the payload.
  21. * `event_headers_key` - The key to use to store all the headers received
  22. * `verbs` - Comma-separated list of http verbs your agent will accept.
  23. For example, "post,get" will enable POST and GET requests. Defaults
  24. to "post".
  25. * `response` - The response message to the request. Defaults to 'Event Created'.
  26. * `response_headers` - An object with any custom response headers. (example: `{"Access-Control-Allow-Origin": "*"}`)
  27. * `code` - The response code to the request. Defaults to '201'. If the code is '301' or '302' the request will automatically be redirected to the url defined in "response".
  28. * `recaptcha_secret` - Setting this to a reCAPTCHA "secret" key makes your agent verify incoming requests with reCAPTCHA. Don't forget to embed a reCAPTCHA snippet including your "site" key in the originating form(s).
  29. * `recaptcha_send_remote_addr` - Set this to true if your server is properly configured to set REMOTE_ADDR to the IP address of each visitor (instead of that of a proxy server).
  30. MD
  31. end
  32. event_description do
  33. <<-MD
  34. The event payload is based on the value of the `payload_path` option,
  35. which is set to `#{interpolated['payload_path']}`.
  36. MD
  37. end
  38. def default_options
  39. { "secret" => "supersecretstring",
  40. "expected_receive_period_in_days" => 1,
  41. "payload_path" => "some_key",
  42. "event_headers" => "",
  43. "event_headers_key" => "headers"
  44. }
  45. end
  46. def receive_web_request(request)
  47. params = request.params.except(:action, :controller, :agent_id, :user_id, :format)
  48. method = request.method_symbol.to_s
  49. headers = request.headers.each_with_object({}) { |(name, value), hash|
  50. case name
  51. when /\AHTTP_([A-Z0-9_]+)\z/
  52. hash[$1.tr('_', '-').gsub(/[^-]+/, &:capitalize)] = value
  53. end
  54. }
  55. # check the secret
  56. secret = params.delete('secret')
  57. return ["Not Authorized", 401] unless secret == interpolated['secret']
  58. # check the verbs
  59. verbs = (interpolated['verbs'] || 'post').split(/,/).map { |x| x.strip.downcase }.select { |x| x.present? }
  60. return ["Please use #{verbs.join('/').upcase} requests only", 401] unless verbs.include?(method)
  61. # check the code
  62. code = (interpolated['code'].presence || 201).to_i
  63. # check the reCAPTCHA response if required
  64. if recaptcha_secret = interpolated['recaptcha_secret'].presence
  65. recaptcha_response = params.delete('g-recaptcha-response') or
  66. return ["Not Authorized", 401]
  67. parameters = {
  68. secret: recaptcha_secret,
  69. response: recaptcha_response,
  70. }
  71. if boolify(interpolated['recaptcha_send_remote_addr'])
  72. parameters[:remoteip] = request.env['REMOTE_ADDR']
  73. end
  74. begin
  75. response = faraday.post('https://www.google.com/recaptcha/api/siteverify',
  76. parameters)
  77. rescue => e
  78. error "Verification failed: #{e.message}"
  79. return ["Not Authorized", 401]
  80. end
  81. JSON.parse(response.body)['success'] or
  82. return ["Not Authorized", 401]
  83. end
  84. [payload_for(params)].flatten.each do |payload|
  85. create_event(payload: payload.merge(event_headers_payload(headers)))
  86. end
  87. if interpolated['response_headers'].presence
  88. [interpolated(params)['response'] || 'Event Created', code, "text/plain", interpolated['response_headers'].presence]
  89. else
  90. [interpolated(params)['response'] || 'Event Created', code]
  91. end
  92. end
  93. def working?
  94. event_created_within?(interpolated['expected_receive_period_in_days']) && !recent_error_logs?
  95. end
  96. def validate_options
  97. unless options['secret'].present?
  98. errors.add(:base, "Must specify a secret for 'Authenticating' requests")
  99. end
  100. if options['code'].present? && options['code'].to_s !~ /\A\s*(\d+|\{.*)\s*\z/
  101. errors.add(:base, "Must specify a code for request responses")
  102. end
  103. if options['code'].to_s.in?(['301', '302']) && !options['response'].present?
  104. errors.add(:base, "Must specify a url for request redirect")
  105. end
  106. validate_event_headers_options!
  107. end
  108. def payload_for(params)
  109. Utils.value_at(params, interpolated['payload_path']) || {}
  110. end
  111. end
  112. end