Class: Shamu::Features::ToggleCodec

Inherits:
Object
  • Object
show all
Includes:
Security::HashedValue
Defined in:
lib/shamu/features/toggle_codec.rb

Overview

Packs and unpacks sticky toggle settings in a securely verifiable way. The data is not encrypted so it should not be relied on for security. It only guarantees that the packed data was created by calling ToggleCode#pack.

Instance Method Summary collapse

Methods included from Security::HashedValue

#hash_value

Constructor Details

#initialize(private_key = Shamu::Security.private_key) ⇒ ToggleCodec

Returns a new instance of ToggleCodec.

Parameters:

  • private_key (String) (defaults to: Shamu::Security.private_key)

    the private key used to verify the packed toggles.



12
13
14
# File 'lib/shamu/features/toggle_codec.rb', line 12

def initialize( private_key = Shamu::Security.private_key )
  @private_key = private_key
end

Instance Method Details

#insecure_pack(toggles) ⇒ String

Packs a hash of configured features without any authentication guarantees. Useful for working with trusted sources such as ENV variables.

Parameters:

  • featues (Hash<String,Boolean>)

    hash of name to enabled state.

Returns:

  • (String)

    the packed string.



32
33
34
35
36
37
38
# File 'lib/shamu/features/toggle_codec.rb', line 32

def insecure_pack( toggles )
  toggles.each_with_object("") do |(key, state), packed|
    packed << "," unless packed.blank?
    packed << "!" unless state
    packed << key
  end
end

#insecure_unpack(token) ⇒ Hash<String,Boolean>

Unpack a insecure packed token into its original hash of configured toggles. If the token is invalid an empty result is returned.

Parameters:

  • token (String)

    the packed toggles

Returns:

  • (Hash<String,Boolean>)

    the configured toggles.



56
57
58
59
60
61
62
63
64
65
# File 'lib/shamu/features/toggle_codec.rb', line 56

def insecure_unpack( token )
  return {} unless token

  token.split( "," ).each_with_object( {} ) do |toggle, hash|
    bang = toggle[0] == "!"
    key  = bang ? toggle[1..-1] : toggle

    hash[key] = !bang
  end
end

#pack(toggles) ⇒ String

Packs a hash of configured features into a string that can be sent from a client at a later date to override those features. Use #unpack to restore the features hash.

Parameters:

  • featues (Hash<String,Boolean>)

    hash of name to enabled state.

Returns:

  • (String)

    the packed string.



22
23
24
# File 'lib/shamu/features/toggle_codec.rb', line 22

def pack( toggles )
  hash_value( insecure_pack( toggles ) )
end

#unpack(token) ⇒ Hash<String,Boolean>

Unpack a packed token into its original hash of configured toggles. If the token is invalid or unauthenticated an empty result is returned.

Parameters:

  • token (String)

    the packed toggles

Returns:

  • (Hash<String,Boolean>)

    the configured toggles.



46
47
48
# File 'lib/shamu/features/toggle_codec.rb', line 46

def unpack( token )
  insecure_unpack( verify_hash( token ) )
end