robust_server_socket 0.4.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,8 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module RobustServerSocket
2
4
  module Configuration
3
- MIN_KEY_SIZE = 2048
5
+ ConfigurationError = Class.new(StandardError)
4
6
 
5
7
  attr_reader :configuration, :configured
6
8
 
@@ -15,6 +17,7 @@ module RobustServerSocket
15
17
  def configure
16
18
  @configuration ||= ConfigStore.new
17
19
  yield(configuration)
20
+ validate_configuration!
18
21
  validate_key_security!
19
22
 
20
23
  @configured = true
@@ -37,21 +40,26 @@ module RobustServerSocket
37
40
 
38
41
  private
39
42
 
43
+ def validate_configuration!
44
+ validate_positive!(:rate_limit_max_requests)
45
+ validate_positive!(:rate_limit_window_seconds)
46
+ validate_positive!(:token_expiration_time)
47
+ end
48
+
49
+ def validate_positive!(attr)
50
+ return if configuration.public_send(attr).to_i.positive?
51
+
52
+ raise ConfigurationError, "#{attr} must be positive"
53
+ end
54
+
40
55
  def validate_key_security!
41
- key = ::OpenSSL::PKey::RSA.new(configuration.private_key)
42
- key_bits = key.n.num_bits
43
-
44
- if key_bits < MIN_KEY_SIZE
45
- raise SecurityError,
46
- "RSA key size (#{key_bits} bits) below minimum (#{MIN_KEY_SIZE} bits)"
47
- end
48
- rescue ::OpenSSL::PKey::RSAError => e
49
- raise SecurityError, "Invalid private key: #{e.message}"
56
+ TokenCipher.read_private_key(configuration.private_key, cipher: configuration.cipher)
50
57
  end
51
58
  end
52
59
 
53
60
  class ConfigStore
54
- attr_accessor :allowed_services, :private_key, :token_expiration_time, :store_used_token_time, :redis_url, :redis_pass,
61
+ attr_accessor :allowed_services, :private_key, :token_expiration_time,
62
+ :redis_url, :redis_pass, :cipher,
55
63
  :rate_limit_max_requests, :rate_limit_window_seconds, :using_modules
56
64
 
57
65
  attr_reader :_modules_check_rows, :_bang_modules_check_rows
@@ -59,14 +67,9 @@ module RobustServerSocket
59
67
  def initialize
60
68
  @rate_limit_max_requests = 100
61
69
  @rate_limit_window_seconds = 60
62
- @store_used_token_time = 600
63
70
  @token_expiration_time = 10
64
- @using_modules = %i[
65
- client_auth_protection
66
- dos_attack_protection
67
- replay_attack_protection
68
- ]
69
-
71
+ @cipher = :x25519
72
+ @using_modules = %i[client_auth_protection rate_limit_protection replay_attack_protection]
70
73
  @_modules_check_rows = []
71
74
  @_bang_modules_check_rows = []
72
75
  end
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module RobustServerSocket
2
4
  module Modules
3
5
  module ClientAuthProtection
@@ -1,16 +1,18 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require_relative '../cacher'
2
4
  require_relative '../rate_limiter'
3
5
 
4
6
  module RobustServerSocket
5
7
  module Modules
6
- module DosAttackProtection
8
+ module RateLimitProtection
7
9
  def self.included(_base)
8
10
  RobustServerSocket._push_modules_check_code('validate_rate_limit')
9
11
  RobustServerSocket._push_bang_modules_check_code("validate_rate_limit!\n")
10
12
  end
11
13
 
12
14
  def validate_rate_limit
13
- !!RateLimiter.check(client)
15
+ RateLimiter.check(client)
14
16
  end
15
17
 
16
18
  def validate_rate_limit!
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require_relative '../cacher'
2
4
 
3
5
  module RobustServerSocket
@@ -13,28 +15,15 @@ module RobustServerSocket
13
15
 
14
16
  def atomic_validate_and_log_token!
15
17
  result = Cacher.atomic_validate_and_log(
16
- decrypted_token,
17
- store_used_token_time,
18
- timestamp,
19
- token_expiration_time
18
+ decrypted_token, store_used_token_time, timestamp, token_expiration_time
20
19
  )
21
-
22
- case result
23
- when 'ok'
24
- true
25
- when 'stale'
26
- raise StaleToken
27
- when 'used'
28
- raise UsedToken
29
- else
30
- raise StandardError, "Unexpected result: #{result}"
31
- end
20
+ handle_validation_result!(result)
32
21
  end
33
22
 
34
23
  def atomic_validate_and_log_token
35
24
  Cacher.atomic_validate_and_log(
36
25
  decrypted_token,
37
- store_used_token_time, # window for storing used token
26
+ store_used_token_time,
38
27
  timestamp,
39
28
  token_expiration_time
40
29
  ) == 'ok'
@@ -42,8 +31,17 @@ module RobustServerSocket
42
31
 
43
32
  private
44
33
 
34
+ def handle_validation_result!(result)
35
+ case result
36
+ when 'ok' then true
37
+ when 'stale' then raise StaleToken
38
+ when 'used' then raise UsedToken
39
+ else raise StandardError, "Unexpected result: #{result}"
40
+ end
41
+ end
42
+
45
43
  def store_used_token_time
46
- RobustServerSocket.configuration.store_used_token_time
44
+ RobustServerSocket.configuration.token_expiration_time + Cacher::CLOCK_SKEW_MS / 1000
47
45
  end
48
46
  end
49
47
  end
@@ -1,30 +1,20 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module RobustServerSocket
2
4
  class RateLimiter
3
5
  RateLimitExceeded = Class.new(StandardError)
4
6
 
5
7
  class << self
6
8
  def check!(client_name)
7
- unless (attempts = check(client_name))
8
- actual_attempts = current_attempts(client_name)
9
-
10
- raise RateLimitExceeded, "Rate limit exceeded for #{client_name}: #{actual_attempts}/#{max_requests} requests per #{window_seconds}s"
11
- end
9
+ return if check(client_name)
12
10
 
13
- attempts
11
+ raise RateLimitExceeded,
12
+ "Rate limit exceeded for #{client_name}: max #{max_requests} per #{window_seconds}s"
14
13
  end
15
14
 
16
15
  def check(client_name)
17
- key = rate_limit_key(client_name)
18
- attempts = increment_attempts(key)
19
-
20
- return false if attempts > max_requests
21
-
22
- attempts
23
- end
24
-
25
- def current_attempts(client_name)
26
- key = rate_limit_key(client_name)
27
- Cacher.get(key).to_i
16
+ attempts = record_attempt(client_name)
17
+ attempts <= max_requests
28
18
  end
29
19
 
30
20
  def reset!(client_name)
@@ -39,16 +29,11 @@ module RobustServerSocket
39
29
 
40
30
  private
41
31
 
42
- def increment_attempts(key)
43
- Cacher.with_redis do |conn|
44
- attempts = conn.incr(key)
45
- # Set expiration only on first attempt to ensure atomic window
46
- conn.expire(key, window_seconds) if attempts == 1
47
- attempts
48
- end
32
+ def record_attempt(client_name)
33
+ Cacher.incr_sliding_window_count(rate_limit_key(client_name), window_seconds)
49
34
  rescue Cacher::RedisConnectionError => e
50
- handle_redis_error(e, 'increment_attempts')
51
- 0 # Fail open: allow request if Redis is down
35
+ handle_redis_error(e, 'record_attempt')
36
+ 0
52
37
  end
53
38
 
54
39
  def rate_limit_key(client_name)
@@ -1,37 +1,22 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module RobustServerSocket
2
4
  module SecureToken
3
- BASE64_REGEXP = /\A[A-Za-z0-9+\/]*={0,2}\z/.freeze
4
- InvalidToken = Class.new(StandardError)
5
-
6
5
  module Decrypt
7
6
  class << self
8
7
  def call(token)
9
- unless token.is_a?(String) && token.match?(BASE64_REGEXP)
10
- raise InvalidToken, 'Invalid token format'
11
- end
12
-
13
- decoded_token = ::Base64.strict_decode64(token)
14
-
15
- if decoded_token.bytesize > 1024
16
- raise InvalidToken, 'Token too large'
17
- end
18
-
19
- private_key.private_decrypt(decoded_token, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING).force_encoding('UTF-8')
20
- rescue ::OpenSSL::PKey::RSAError, ArgumentError
21
- raise InvalidToken, 'Invalid token'
8
+ TokenCipher.open(token, private_key_pem, cipher: RobustServerSocket.configuration.cipher)
22
9
  end
23
10
 
24
11
  # Clear cached private key (useful for hot reloading in development)
25
12
  def clear_private_key_cache!
26
- @private_key = nil
13
+ @private_key_pem = nil
27
14
  end
28
15
 
29
16
  private
30
17
 
31
- # Cache RSA private key at module level for the lifetime of the Rails process
32
- # This avoids recreating the RSA object on every token decryption
33
- def private_key
34
- @private_key ||= ::OpenSSL::PKey::RSA.new(RobustServerSocket.configuration.private_key)
18
+ def private_key_pem
19
+ @private_key_pem ||= RobustServerSocket.configuration.private_key
35
20
  end
36
21
  end
37
22
  end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RobustServerSocket
4
+ module SecureToken
5
+ BASE64_REGEXP = %r{\A[A-Za-z0-9+/]+={0,2}\z}.freeze
6
+ InvalidToken = Class.new(StandardError)
7
+ end
8
+ end
@@ -0,0 +1,153 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'openssl'
4
+ require 'base64'
5
+
6
+ module RobustServerSocket
7
+ # A named asymmetric token scheme. Built-ins are X25519 and X448.
8
+ # Register your own with CipherRegistry.register(:name, scheme).
9
+ # A scheme answers open(token, private_key_pem) and read_private_key(pem).
10
+ module CipherRegistry
11
+ UnknownCipher = Class.new(SecurityError)
12
+
13
+ @schemes = {}
14
+
15
+ class << self
16
+ def register(name, scheme)
17
+ raise ArgumentError, 'cipher name must be a Symbol' unless name.is_a?(Symbol)
18
+ raise ArgumentError, 'cipher must answer open and read_private_key' unless scheme.respond_to?(:open) && scheme.respond_to?(:read_private_key)
19
+
20
+ @schemes[name] = scheme
21
+ name
22
+ end
23
+
24
+ def fetch(name)
25
+ @schemes.fetch(name.to_sym) { raise UnknownCipher, "Unknown cipher: #{name}" }
26
+ end
27
+
28
+ def registered?(name)
29
+ @schemes.key?(name.to_sym)
30
+ end
31
+ end
32
+ end
33
+
34
+ module EcdhCipher
35
+ IV_LENGTH = 12
36
+ TAG_LENGTH = 16
37
+ KEY_LENGTH = 32
38
+ MAX_BLOB_BYTES = 1024
39
+
40
+ def self.build(algorithm, ephemeral_der_length)
41
+ Module.new do
42
+ extend self
43
+
44
+ const_set(:ALGORITHM, algorithm)
45
+ const_set(:EPHEMERAL_DER_LENGTH, ephemeral_der_length)
46
+ const_set(:HEADER_LENGTH, ephemeral_der_length + IV_LENGTH + TAG_LENGTH)
47
+ const_set(:INFO, "robust-socket-token-v1-#{algorithm.downcase}")
48
+
49
+ def seal(plaintext, public_key_pem)
50
+ recipient = OpenSSL::PKey.read(public_key_pem)
51
+ raise SecurityError, 'Invalid public key' unless recipient.oid == self::ALGORITHM
52
+
53
+ ephemeral = OpenSSL::PKey.generate_key(self::ALGORITHM)
54
+ blob = ephemeral.public_to_der.b + gcm_seal(derive_key(ephemeral.derive(recipient)), plaintext)
55
+
56
+ ::Base64.strict_encode64(blob)
57
+ end
58
+
59
+ def open(token, private_key_pem)
60
+ raise SecureToken::InvalidToken, 'Invalid token format' unless token.is_a?(String) && token.match?(SecureToken::BASE64_REGEXP)
61
+
62
+ decoded = ::Base64.strict_decode64(token)
63
+ raise SecureToken::InvalidToken, 'Token too large' if decoded.bytesize > EcdhCipher::MAX_BLOB_BYTES
64
+ raise SecureToken::InvalidToken, 'Invalid token' if decoded.bytesize <= self::HEADER_LENGTH
65
+
66
+ ephemeral_der = decoded.byteslice(0, self::EPHEMERAL_DER_LENGTH)
67
+ iv = decoded.byteslice(self::EPHEMERAL_DER_LENGTH, EcdhCipher::IV_LENGTH)
68
+ tag = decoded.byteslice(self::EPHEMERAL_DER_LENGTH + EcdhCipher::IV_LENGTH, EcdhCipher::TAG_LENGTH)
69
+ ciphertext = decoded.byteslice(self::HEADER_LENGTH..-1)
70
+ key = derive_key(read_private_key(private_key_pem).derive(read_ephemeral(ephemeral_der)))
71
+
72
+ gcm_open(key, iv, tag, ciphertext)
73
+ rescue OpenSSL::PKey::PKeyError, OpenSSL::Cipher::CipherError, ArgumentError
74
+ raise SecureToken::InvalidToken, 'Invalid token'
75
+ end
76
+
77
+ def read_private_key(pem)
78
+ key = OpenSSL::PKey.read(pem)
79
+ raise SecurityError, 'Invalid private key' unless private_key?(key)
80
+
81
+ key
82
+ rescue OpenSSL::PKey::PKeyError => e
83
+ raise SecurityError, "Invalid private key: #{e.message}"
84
+ end
85
+
86
+ def private_key?(key)
87
+ key.oid == self::ALGORITHM && holds_private_key?(key)
88
+ end
89
+
90
+ def holds_private_key?(key)
91
+ !key.raw_private_key.nil?
92
+ rescue OpenSSL::PKey::PKeyError
93
+ false
94
+ end
95
+
96
+ def read_ephemeral(der)
97
+ key = OpenSSL::PKey.read(der)
98
+ raise OpenSSL::PKey::PKeyError, 'invalid ephemeral key' unless key.oid == self::ALGORITHM && !holds_private_key?(key)
99
+
100
+ key
101
+ end
102
+
103
+ def derive_key(shared_secret)
104
+ OpenSSL::KDF.hkdf(shared_secret, salt: '', info: self::INFO, length: EcdhCipher::KEY_LENGTH, hash: 'SHA256')
105
+ end
106
+
107
+ def gcm_seal(key, plaintext)
108
+ cipher = OpenSSL::Cipher.new('aes-256-gcm')
109
+ cipher.encrypt
110
+ cipher.key = key
111
+ iv = cipher.random_iv
112
+ cipher.auth_data = self::INFO
113
+ ciphertext = cipher.update(plaintext) + cipher.final
114
+
115
+ iv + cipher.auth_tag + ciphertext
116
+ end
117
+
118
+ def gcm_open(key, iv, tag, ciphertext)
119
+ cipher = OpenSSL::Cipher.new('aes-256-gcm')
120
+ cipher.decrypt
121
+ cipher.key = key
122
+ cipher.iv = iv
123
+ cipher.auth_tag = tag
124
+ cipher.auth_data = self::INFO
125
+
126
+ (cipher.update(ciphertext) + cipher.final).force_encoding('UTF-8')
127
+ end
128
+ end
129
+ end
130
+ end
131
+
132
+ X25519 = EcdhCipher.build('X25519', 44)
133
+ X448 = EcdhCipher.build('X448', 68)
134
+
135
+ CipherRegistry.register(:x25519, X25519)
136
+ CipherRegistry.register(:x448, X448)
137
+
138
+ module TokenCipher
139
+ module_function
140
+
141
+ def seal(plaintext, public_key_pem, cipher: :x25519)
142
+ CipherRegistry.fetch(cipher).seal(plaintext, public_key_pem)
143
+ end
144
+
145
+ def open(token, private_key_pem, cipher: :x25519)
146
+ CipherRegistry.fetch(cipher).open(token, private_key_pem)
147
+ end
148
+
149
+ def read_private_key(pem, cipher: :x25519)
150
+ CipherRegistry.fetch(cipher).read_private_key(pem)
151
+ end
152
+ end
153
+ end
@@ -6,6 +6,8 @@ require 'redis'
6
6
  require 'connection_pool'
7
7
 
8
8
  require_relative 'robust_server_socket/configuration'
9
+ require_relative 'robust_server_socket/secure_token'
10
+ require_relative 'robust_server_socket/token_cipher'
9
11
  require_relative 'robust_server_socket/secure_token/decrypt'
10
12
  require_relative 'robust_server_socket/client_token'
11
13
 
@@ -14,17 +16,17 @@ module RobustServerSocket
14
16
 
15
17
  module_function
16
18
 
17
- def load!
19
+ def load! # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength
18
20
  raise 'You must correctly configure RobustServerSocket first!' unless configured?
19
21
 
20
22
  configuration.using_modules.each do |mod|
21
23
  raise ArgumentError, 'Module must be a Symbol!' unless mod.is_a?(Symbol)
22
24
 
23
25
  require_relative "robust_server_socket/modules/#{mod}"
24
- ClientToken.include eval(mod.to_s.split('_').map(&:capitalize).unshift('Modules::').join)
26
+ ClientToken.include const_get(mod.to_s.split('_').map(&:capitalize).unshift('Modules::').join)
25
27
  end
26
28
 
27
- ClientToken.class_eval(<<~METHOD)
29
+ ClientToken.class_eval(<<~METHOD, __FILE__, __LINE__ + 1)
28
30
  def modules_checks
29
31
  #{(RobustServerSocket.configuration._modules_check_rows.empty? ? ['true'] : RobustServerSocket.configuration._modules_check_rows.map(&:strip)).join(' && ')}
30
32
  end
data/lib/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module RobustServerSocket
4
- VERSION = '0.4.2'
4
+ VERSION = '0.6.0'
5
5
  end
@@ -1,16 +1,16 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "./lib/version"
3
+ require './lib/version'
4
4
 
5
5
  Gem::Specification.new do |spec|
6
- spec.name = "robust_server_socket"
6
+ spec.name = 'robust_server_socket'
7
7
  spec.version = RobustServerSocket::VERSION
8
- spec.authors = ["tee_zed"]
9
- spec.email = ["tee0zed@gmail.com"]
10
- spec.description = "Robust Server Socket"
11
- spec.summary = "Robust Server Socket gem for RobustPro"
12
- spec.license = "MIT"
13
- spec.required_ruby_version = ">= 2.7.0"
8
+ spec.authors = ['tee_zed']
9
+ spec.email = ['tee0zed@gmail.com']
10
+ spec.description = 'Robust Server Socket'
11
+ spec.summary = 'Robust Server Socket gem for RobustPro'
12
+ spec.license = 'MIT'
13
+ spec.required_ruby_version = '>= 2.7.0'
14
14
 
15
15
  # Specify which files should be added to the gem when it is released.
16
16
  # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
@@ -20,13 +20,14 @@ Gem::Specification.new do |spec|
20
20
  f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor Gemfile])
21
21
  end
22
22
  end
23
- spec.bindir = "exe"
23
+ spec.bindir = 'exe'
24
24
  spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
25
- spec.require_paths = ["lib"]
26
- spec.add_dependency 'rspec'
25
+ spec.require_paths = ['lib']
26
+ spec.add_dependency 'base64'
27
+ spec.add_dependency 'hiredis'
27
28
  spec.add_dependency 'rake'
28
29
  spec.add_dependency 'redis'
29
- spec.add_dependency 'hiredis'
30
+ spec.add_dependency 'rspec'
30
31
 
31
32
  # Uncomment to register a new dependency of your gem
32
33
  # spec.add_dependency "example-gem", "~> 1.0"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: robust_server_socket
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.2
4
+ version: 0.6.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - tee_zed
@@ -10,7 +10,21 @@ cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
- name: rspec
13
+ name: base64
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '0'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '0'
26
+ - !ruby/object:Gem::Dependency
27
+ name: hiredis
14
28
  requirement: !ruby/object:Gem::Requirement
15
29
  requirements:
16
30
  - - ">="
@@ -52,7 +66,7 @@ dependencies:
52
66
  - !ruby/object:Gem::Version
53
67
  version: '0'
54
68
  - !ruby/object:Gem::Dependency
55
- name: hiredis
69
+ name: rspec
56
70
  requirement: !ruby/object:Gem::Requirement
57
71
  requirements:
58
72
  - - ">="
@@ -73,6 +87,8 @@ extensions: []
73
87
  extra_rdoc_files: []
74
88
  files:
75
89
  - ".rspec"
90
+ - ".rubocop.yml"
91
+ - ".ruby-version"
76
92
  - CODE_OF_CONDUCT.md
77
93
  - LICENSE.txt
78
94
  - README.en.md
@@ -83,10 +99,12 @@ files:
83
99
  - lib/robust_server_socket/client_token.rb
84
100
  - lib/robust_server_socket/configuration.rb
85
101
  - lib/robust_server_socket/modules/client_auth_protection.rb
86
- - lib/robust_server_socket/modules/dos_attack_protection.rb
102
+ - lib/robust_server_socket/modules/rate_limit_protection.rb
87
103
  - lib/robust_server_socket/modules/replay_attack_protection.rb
88
104
  - lib/robust_server_socket/rate_limiter.rb
105
+ - lib/robust_server_socket/secure_token.rb
89
106
  - lib/robust_server_socket/secure_token/decrypt.rb
107
+ - lib/robust_server_socket/token_cipher.rb
90
108
  - lib/version.rb
91
109
  - robust_server_socket.gemspec
92
110
  licenses: