Module: Slosilo::HTTPRequest

Defined in:
lib/slosilo/http_request.rb

Overview

A mixin module which simplifies generating signed and encrypted requests. It’s designed to be mixed into a standard Net::HTTPRequest object and ensures the request is signed and optionally encrypted before execution. Requests prepared this way will be recognized by Slosilo::Rack::Middleware.

As an example, you can use it with RestClient like so:

RestClient.add_before_execution_proc do |req, params|
  require 'slosilo'
  req.extend Slosilo::HTTPRequest
  req.keyname = :somekey
end

The request won’t be encrypted unless you set the destination keyname.

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#keynameObject

Name of the key used to encrypt the request. Use it to establish the identity of the receiver.



57
58
59
# File 'lib/slosilo/http_request.rb', line 57

def keyname
  @keyname
end

Instance Method Details

#encrypt!Object

Encrypt the request with key named @keyname from Slosilo::Keystore. If calling this manually, make sure to encrypt before signing.



19
20
21
22
23
24
# File 'lib/slosilo/http_request.rb', line 19

def encrypt!
  return unless @keyname
  return unless body && !body.empty?
  self.body, key = Slosilo[@keyname].encrypt body
  self['X-Slosilo-Key'] = Base64::urlsafe_encode64 key
end

#exec(*a) ⇒ Object

Encrypt, sign and execute the request.



47
48
49
50
51
52
53
# File 'lib/slosilo/http_request.rb', line 47

def exec *a
  # we need to hook here because the body might be set
  # in several ways and here it's hopefully finalized
  encrypt!
  sign!
  super *a
end

#sign!Object

Sign the request with :own key from Slosilo::Keystore. If calling this manually, make sure to encrypt before signing.



28
29
30
31
32
# File 'lib/slosilo/http_request.rb', line 28

def sign!
  token = Slosilo[:own].signed_token signed_data
  self['Timestamp'] = token["timestamp"]
  self['X-Slosilo-Signature'] = token["signature"]
end

#signed_dataObject

Build the data hash to sign.



35
36
37
38
39
40
41
42
43
44
# File 'lib/slosilo/http_request.rb', line 35

def signed_data
  data = { "path" => path, "body" => [body].pack('m0') }
  if key = self['X-Slosilo-Key']
    data["key"] = key
  end
  if authz = self['Authorization']
    data["authorization"] = authz
  end
  data
end