Class: Machina::WebhookReceiver

Inherits:
Object
  • Object
show all
Defined in:
lib/machina/webhook_receiver.rb

Overview

Verifies and processes inbound webhook events from the Machina Console, invalidating or marking cached sessions as stale when permissions change.

Instance Method Summary collapse

Constructor Details

#initialize(request, cache: Machina.cache) ⇒ WebhookReceiver

Returns a new instance of WebhookReceiver.



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/machina/webhook_receiver.rb', line 7

def initialize(request, cache: Machina.cache)
  @cache = cache
  @request = request
  @raw_body = request.body.read

  request.body.rewind if request.body.respond_to?(:rewind)

  @event = request.headers['X-Machina-Event']
  @signature = request.headers['X-Machina-Signature'].to_s
  @payload = @raw_body.present? ? JSON.parse(@raw_body) : {}
end

Instance Method Details

#process!Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/machina/webhook_receiver.rb', line 27

def process!
  return false unless valid?

  case event
  when 'permissions.changed'
    mark_stale(payload['user_id'], payload['workspace_id'])
  when 'organization.member_removed'
    invalidate_all_sessions
  when 'workspace.member_removed'
    invalidate_user_sessions(payload['user_id'], payload['workspace_id'])
  when 'workspace.deleted', 'workspace.product_disabled'
    invalidate_workspace(payload['workspace_id'])
  end

  true
end

#valid?Boolean

Returns:

  • (Boolean)


19
20
21
22
23
24
25
# File 'lib/machina/webhook_receiver.rb', line 19

def valid?
  return false if signature.blank?

  signing_key = Digest::SHA256.hexdigest(Machina.config.service_token.to_s)
  expected = OpenSSL::HMAC.hexdigest('SHA256', signing_key, raw_body)
  ActiveSupport::SecurityUtils.secure_compare(expected, signature)
end