Sha256: cf0e15460a2ef2d428676255c5e469bc17ec62d67d8052f3ec1bc99af15eb0ad

Contents?: true

Size: 1.78 KB

Versions: 2

Compression:

Stored size: 1.78 KB

Contents

# frozen_string_literal: true

module Rodbot
  class Plugins
    class GithubWebhook
      module App

        class Routes < ::App
          DEFAULT_HANDLER = ->(request) do
            if request.env['HTTP_X_GITHUB_EVENT'] == 'workflow_run'
              json = JSON.parse(request.body.read)
              project = json.dig('repository', 'full_name')
              status = json.dig('workflow_run', 'status')
              status = json.dig('workflow_run', 'conclusion') if status == 'completed'
              emoji = case status
                when 'requested' then '🟡'
                when 'success' then '🟢'
                when 'failure' then '🔴'
                else '⚪️'
              end
              [emoji, project, status.gsub('_', ' ')].join(' ')
            end
          end

          route do |r|
            r.post '' do
              r.halt 200 if request.env['HTTP_X_GITHUB_EVENT'] == 'ping'
              r.halt 401 unless authorized?
              handler = Rodbot.config(:plugin, :github_webhook, :handler) || DEFAULT_HANDLER
              message = handler.call(r)
              if message&.empty?
                r.halt 204
              else
                Rodbot.say message
                r.halt 200
              end
            end
          rescue => error
            r.halt 500, error.message
          end

          private

          def authorized?
            Rodbot.config(:plugin, :github_webhook, :secret_tokens).to_s.split(':').any? do |secret|
              signature = 'sha256=' + OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), secret, request.body.read)
              request.body.rewind
              ::Rack::Utils.secure_compare(signature, request.env['HTTP_X_HUB_SIGNATURE_256'])
            end
          end

        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rodbot-0.5.1 lib/rodbot/plugins/github_webhook/app.rb
rodbot-0.5.0 lib/rodbot/plugins/github_webhook/app.rb