Class: Warren::MessageFilter::SharedSecret

Inherits:
Object
  • Object
show all
Defined in:
lib/warren/filters/shared_secret.rb

Overview

Hashes the message using a secret salt, stores the hash in the message and then checks its the same when pulled off the other end.

Basic trust implementation to make sure the message hasn’t been tampered with in transit and came from an “authorised” app.

Make sure both the publisher and subscriber use the same key else you’ll get KeyValidationError error raised.

Defined Under Namespace

Classes: KeyValidationError, NoKeyError

Class Method Summary collapse

Class Method Details

.keyObject

Returns the current key Raises NoKeyError if no key has been assigned yet

Raises:



34
35
36
37
# File 'lib/warren/filters/shared_secret.rb', line 34

def self.key
  raise NoKeyError if @@key.nil?
  @@key
end

.key=(key) ⇒ Object

Sets the key to use



28
29
30
# File 'lib/warren/filters/shared_secret.rb', line 28

def self.key= key
  @@key = key
end

.pack(msg) ⇒ Object

Called when the message is being packed for transit. Returns a hash.



50
51
52
53
54
55
56
# File 'lib/warren/filters/shared_secret.rb', line 50

def self.pack msg
  # Make sure its a hash
  msg = {:secret_msg => msg} unless msg.is_a? Hash
  # And add our secret into the hash
  msg[:secret] = self.secret(msg.to_s)
  msg
end

.secret(msg) ⇒ Object

Returns the hashed message

Expects that msg#to_s returns a string to hash against.



44
45
46
# File 'lib/warren/filters/shared_secret.rb', line 44

def self.secret msg
  HMAC::SHA256.hexdigest(self.key, msg.to_s)
end

.unpack(msg) ⇒ Object

Called when unpacking the message from transit. Returns the original object.

Raises:



60
61
62
63
64
65
66
# File 'lib/warren/filters/shared_secret.rb', line 60

def self.unpack msg
  # Check the secret exists in the msg and matches the secret_string
  raise KeyValidationError unless msg.delete(:secret) == self.secret(msg)
  # see if its a hash we created, it'll only contain the key "secret_msg" if it is
  msg = msg[:secret_msg] if msg.keys == [:secret_msg]
  msg
end