Class: Volt::MessageBus::MessageEncoder

Inherits:
Object
  • Object
show all
Defined in:
lib/volt/server/message_bus/message_encoder.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeMessageEncoder

Returns a new instance of MessageEncoder.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/volt/server/message_bus/message_encoder.rb', line 7

def initialize
  # rbnacl is not supported on windows.
  windows = Gem.win_platform?

  if windows
    Volt.logger.warn('Currently Message Bus encryption is not supported on windows.')
  end

  # Message bus is encrypted by default
  disable = (msg_bus = Volt.config.message_bus) && msg_bus.disable_encryption
  @encrypted = !windows && (disable != true)

  if @encrypted
    # Setup a RbNaCl simple box for handling encryption
    require 'base64'
    begin
      require 'rbnacl/libsodium'
    rescue LoadError => e
    # Ignore, incase they have libsodium installed locally
    end

    begin
      require 'rbnacl'
    rescue LoadError => e
      Volt.logger.error('Volt requires the rbnacl gem to enable encryption on the message bus.  Add it to the gemfile (and rbnacl-sodium if you don\'t have libsodium installed locally')
      raise e
    end

    if Volt.config.app_secret.blank?
      raise "No app_secret has been specified in Volt.config"
    end

    # use the first 32 chars of the app secret for the encryption key.
    key = Base64.decode64(Volt.config.app_secret)[0..31]

    @encrypt_box = RbNaCl::SimpleBox.from_secret_key(key)
  end
end

Instance Attribute Details

#encryptedObject (readonly)

Returns the value of attribute encrypted.



6
7
8
# File 'lib/volt/server/message_bus/message_encoder.rb', line 6

def encrypted
  @encrypted
end

Instance Method Details

#decrypt(message) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/volt/server/message_bus/message_encoder.rb', line 54

def decrypt(message)
  if @encrypted
    @encrypt_box.decrypt(message)
  else
    message
  end
end

#encrypt(message) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/volt/server/message_bus/message_encoder.rb', line 46

def encrypt(message)
  if @encrypted
    @encrypt_box.encrypt(message)
  else
    message
  end
end

#receive_message(io) ⇒ Object



66
67
68
69
70
71
72
73
# File 'lib/volt/server/message_bus/message_encoder.rb', line 66

def receive_message(io)
  begin
    decrypt(Marshal.load(io))
  rescue EOFError => e
    # We get EOFError when the connection closes, return nil
    nil
  end
end

#send_message(io, message) ⇒ Object



62
63
64
# File 'lib/volt/server/message_bus/message_encoder.rb', line 62

def send_message(io, message)
  Marshal.dump(encrypt(message), io)
end