robust_server_socket 0.3.1

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 37064c5a03f119d17df76cb2eba1bd14b91d0cb4732f0d4aa29505614131966f
4
+ data.tar.gz: b18b44079588faf7a38979174971f928f50eb5c1535f0fc6ade2980ace6ed771
5
+ SHA512:
6
+ metadata.gz: 91e42034b36683bfb0d7c481e9f9ef0e3acfae64d43214c0631bf797dbcbd94756e57288cf9a23f2cff2fccea307f019f0ffa93bfea5f86df2f4e751b171fd87
7
+ data.tar.gz: cd15f31a2c698f54684912f1ba3a1b87e8cca074ae0e0967b3374e861484d8bd45a546df35f42781beb651f4505d439ffbff643c3bb6db662fbe4666a87a7a83
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --require spec_helper
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at tee0zed@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 tee_zed
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # RobustServerSocket
2
+
3
+ Gem for in-service Authorization for using with RobustClientSocket
4
+
5
+ ## Security
6
+
7
+ - RSA-2048 key pair is used for authorization.
8
+ - Authorized client names are stored in token and config
9
+ - Token is staleable
10
+ - Token if one-time use only
11
+ - Blacklist for tokens in redis
12
+
13
+ ## Usage
14
+
15
+ 'config/initializers/robust_server_socket.rb'
16
+
17
+ ```ruby
18
+ RobustServerSocket.configure do |c|
19
+ c.private_key = '-----PRIVATE KEY-----[...]' # private key of the service, from pair of keys by RobustServerSocket
20
+ c.token_expiration_time = 10.minutes # time in seconds for token expiration
21
+ c.allowed_services = %w(core) # list of services allowed to use this service, must be same as service name in keychain in RobustClientSocket
22
+ # so if we have
23
+ # RobustClientSocket.configure do |c|
24
+ # c.keychain = {
25
+ # core: { <<< service name
26
+ # base_uri: 'https://core.payrent.com',
27
+ # public_key: '-----BEGIN PUBLIC KEY-----[...]'
28
+ # },
29
+ # we should add 'core' to allowed_services
30
+ c.redis_url = 'redis://localhost:6379' # redis url for storing tokens
31
+ c.redis_pass = 'password' # redis password
32
+
33
+ # Optional: Rate Limiting (disabled by default)
34
+ c.rate_limit_enabled = true # enable rate limiting per client
35
+ c.rate_limit_max_requests = 100 # maximum requests per window (default: 100)
36
+ c.rate_limit_window_seconds = 60 # time window in seconds (default: 60)
37
+ end
38
+
39
+ RobustServerSocket.load!
40
+ ```
41
+
42
+ and then
43
+
44
+ ```ruby
45
+ token = RobustServerSocket::ClientToken.new(token) # token - is a Bearer from secure-token header
46
+ token.valid? #Boolean check if token is not expired and client is allowed to use this service, main authorization check
47
+ token.client #String name of the client
48
+
49
+ RobustServerSocket::ClientToken.validate!(token) # shortcut for token.valid? and raises specific errors
50
+ ```
51
+ ## Errors
52
+
53
+ `RobustServerSocket::ClientToken::UnauthorizedClient` - client is not allowed to use this service you should add it to allowed_services
54
+ `RobustServerSocket::ClientToken::UsedToken` - token is already used
55
+ `RobustServerSocket::ClientToken::StaleToken` - token is stale over the expiration time
56
+ `RobustServerSocket::ClientToken::InvalidToken` - token decryption failed
57
+ `RobustServerSocket::ClientToken::RateLimitExceeded` - client exceeded rate limit (only when rate limiting is enabled)
58
+
59
+
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/test_*.rb"]
10
+ end
11
+
12
+ task default: :test
@@ -0,0 +1,116 @@
1
+ require_relative 'secure_token/cacher'
2
+ require_relative 'secure_token/decrypt'
3
+ require_relative 'rate_limiter'
4
+
5
+ module RobustServerSocket
6
+ class ClientToken
7
+ TOKEN_REGEXP = /\A(.+)_(\d{10,})\z/.freeze
8
+
9
+ InvalidToken = Class.new(StandardError)
10
+ UnauthorizedClient = Class.new(StandardError)
11
+ UsedToken = Class.new(StandardError)
12
+ StaleToken = Class.new(StandardError)
13
+
14
+ def self.validate!(secure_token)
15
+ new(secure_token).tap do |instance|
16
+ raise InvalidToken unless instance.decrypted_token
17
+ raise UnauthorizedClient unless instance.client
18
+
19
+ RateLimiter.check!(instance.client)
20
+
21
+ result = instance.atomic_validate_and_log_token
22
+
23
+ case result
24
+ when 'stale'
25
+ raise StaleToken
26
+ when 'used'
27
+ raise UsedToken
28
+ when 'ok'
29
+ true
30
+ else
31
+ raise InvalidToken, "Unexpected validation result: #{result}"
32
+ end
33
+ end
34
+ end
35
+
36
+ def initialize(secure_token)
37
+ @secure_token = validate_secure_token_input(secure_token)
38
+ @client = nil
39
+ end
40
+
41
+ def valid?
42
+ !!(decrypted_token &&
43
+ client &&
44
+ RateLimiter.check(client) &&
45
+ atomic_validate_and_log_token == 'ok')
46
+ rescue StandardError
47
+ false
48
+ end
49
+
50
+ def client
51
+ @client ||= begin
52
+ target = client_name.strip
53
+ allowed_clients.detect { |allowed| allowed.eql?(target) }
54
+ end
55
+ end
56
+
57
+ def token_not_expired?
58
+ token_expiration_time > Time.now.utc.to_i - timestamp
59
+ end
60
+
61
+ def atomic_validate_and_log_token
62
+ SecureToken::Cacher.atomic_validate_and_log(
63
+ decrypted_token,
64
+ token_expiration_time + 300,
65
+ timestamp,
66
+ token_expiration_time
67
+ )
68
+ end
69
+
70
+ def decrypted_token
71
+ @decrypted_token ||= SecureToken::Decrypt.call(@secure_token)
72
+ end
73
+
74
+ private
75
+
76
+ def allowed_clients
77
+ ::RobustServerSocket.configuration.allowed_services.map(&:strip)
78
+ end
79
+
80
+ def timestamp
81
+ split_token.last.to_i
82
+ end
83
+
84
+ def client_name
85
+ split_token.first
86
+ end
87
+
88
+ def split_token
89
+ @split_token ||= begin
90
+ match_data = decrypted_token.to_s.match(TOKEN_REGEXP)
91
+ raise InvalidToken, 'Invalid token format' unless match_data
92
+ match_data.captures
93
+ end
94
+ end
95
+
96
+ def token_expiration_time
97
+ RobustServerSocket.configuration.token_expiration_time
98
+ end
99
+
100
+ # Do we need it? It would be useful only if public_key compromised
101
+ # def secure_compare(a, b)
102
+ # return false unless a.bytesize == b.bytesize
103
+ #
104
+ # a.bytes.zip(b.bytes).reduce(0) { |diff, (x, y)| diff | (x ^ y) }.zero?
105
+ # end
106
+
107
+ def validate_secure_token_input(token)
108
+ # Validate token input to prevent injection
109
+ raise InvalidToken, 'Token must be a string' unless token.is_a?(String)
110
+ raise InvalidToken, 'Token cannot be empty' if token.empty?
111
+ raise InvalidToken, 'Token too long' if token.length > 2048
112
+
113
+ token
114
+ end
115
+ end
116
+ end
@@ -0,0 +1,55 @@
1
+ module RobustServerSocket
2
+ module Configuration
3
+ MIN_KEY_SIZE = 2048
4
+
5
+ attr_reader :configuration, :configured
6
+
7
+ def configure
8
+ @configuration ||= ConfigStore.new
9
+ yield(configuration)
10
+ validate_key_security!
11
+
12
+ @configured = true
13
+ end
14
+
15
+ def correct_configuration? # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity
16
+ configuration.allowed_services.is_a?(Array) &&
17
+ configuration.allowed_services.any? &&
18
+ configuration.private_key.is_a?(String) &&
19
+ !configuration.private_key.empty? &&
20
+ configuration.token_expiration_time.is_a?(Integer) &&
21
+ configuration.token_expiration_time.positive? &&
22
+ configuration.redis_url.is_a?(String) &&
23
+ !configuration.redis_url.empty?
24
+ end
25
+
26
+ def configured?
27
+ !!@configured && correct_configuration?
28
+ end
29
+
30
+ private
31
+
32
+ def validate_key_security!
33
+ key = ::OpenSSL::PKey::RSA.new(configuration.private_key)
34
+ key_bits = key.n.num_bits
35
+
36
+ if key_bits < MIN_KEY_SIZE
37
+ raise SecurityError,
38
+ "RSA key size (#{key_bits} bits) below minimum (#{MIN_KEY_SIZE} bits)"
39
+ end
40
+ rescue ::OpenSSL::PKey::RSAError => e
41
+ raise SecurityError, "Invalid private key: #{e.message}"
42
+ end
43
+ end
44
+
45
+ class ConfigStore
46
+ attr_accessor :allowed_services, :private_key, :token_expiration_time, :redis_url, :redis_pass,
47
+ :rate_limit_enabled, :rate_limit_max_requests, :rate_limit_window_seconds
48
+
49
+ def initialize
50
+ @rate_limit_enabled = false
51
+ @rate_limit_max_requests = 100
52
+ @rate_limit_window_seconds = 60
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,80 @@
1
+ require_relative 'secure_token/cacher'
2
+
3
+ module RobustServerSocket
4
+ class RateLimiter
5
+ RateLimitExceeded = Class.new(StandardError)
6
+
7
+ class << self
8
+ def check!(client_name)
9
+ unless (attempts = check(client_name))
10
+ actual_attempts = current_attempts(client_name)
11
+ raise RateLimitExceeded, "Rate limit exceeded for #{client_name}: #{actual_attempts}/#{max_requests} requests per #{window_seconds}s"
12
+ end
13
+
14
+ attempts
15
+ end
16
+
17
+ def check(client_name)
18
+ return 0 unless rate_limit_enabled?
19
+
20
+ key = rate_limit_key(client_name)
21
+ attempts = increment_attempts(key)
22
+
23
+ return false if attempts > max_requests
24
+
25
+ attempts
26
+ end
27
+
28
+ def current_attempts(client_name)
29
+ return 0 unless rate_limit_enabled?
30
+
31
+ key = rate_limit_key(client_name)
32
+ SecureToken::Cacher.get(key).to_i
33
+ end
34
+
35
+ def reset!(client_name)
36
+ key = rate_limit_key(client_name)
37
+ SecureToken::Cacher.with_redis do |conn|
38
+ conn.del(key)
39
+ end
40
+ rescue SecureToken::Cacher::RedisConnectionError => e
41
+ handle_redis_error(e, 'reset')
42
+ nil
43
+ end
44
+
45
+ private
46
+
47
+ def increment_attempts(key)
48
+ SecureToken::Cacher.with_redis do |conn|
49
+ attempts = conn.incr(key)
50
+ # Set expiration only on first attempt to ensure atomic window
51
+ conn.expire(key, window_seconds) if attempts == 1
52
+ attempts
53
+ end
54
+ rescue SecureToken::Cacher::RedisConnectionError => e
55
+ handle_redis_error(e, 'increment_attempts')
56
+ 0 # Fail open: allow request if Redis is down
57
+ end
58
+
59
+ def rate_limit_key(client_name)
60
+ "rate_limit:#{client_name}"
61
+ end
62
+
63
+ def rate_limit_enabled?
64
+ RobustServerSocket.configuration.rate_limit_enabled
65
+ end
66
+
67
+ def max_requests
68
+ RobustServerSocket.configuration.rate_limit_max_requests
69
+ end
70
+
71
+ def window_seconds
72
+ RobustServerSocket.configuration.rate_limit_window_seconds
73
+ end
74
+
75
+ def handle_redis_error(error, operation)
76
+ warn "[RateLimiter] Redis error during #{operation}: #{error.class} - #{error.message}"
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,138 @@
1
+ require 'redis'
2
+ require 'connection_pool'
3
+
4
+ module RobustServerSocket
5
+ module SecureToken
6
+ module Cacher
7
+ class RedisConnectionError < StandardError; end
8
+
9
+ class << self
10
+ # Atomically validate token: check expiration and usage, then mark as used
11
+ # Returns: 'ok', 'stale', or 'used'
12
+ def atomic_validate_and_log(key, ttl, timestamp, expiration_time)
13
+ current_time = Time.now.utc.to_i
14
+
15
+ redis.with do |conn|
16
+ conn.eval(
17
+ lua_atomic_validate,
18
+ keys: [key],
19
+ argv: [ttl, timestamp, expiration_time, current_time]
20
+ )
21
+ end
22
+ rescue ::Redis::BaseConnectionError => e
23
+ handle_redis_error(e, 'atomic_validate_and_log')
24
+ raise RedisConnectionError, "Failed to validate token: #{e.message}"
25
+ end
26
+
27
+ def incr(key, ttl = nil)
28
+ ttl_value = ttl || ttl_seconds
29
+
30
+ redis.with do |conn|
31
+ conn.pipelined do |pipeline|
32
+ pipeline.incrby(key, 1)
33
+ pipeline.expire(key, ttl_value)
34
+ end
35
+ end
36
+ rescue ::Redis::BaseConnectionError => e
37
+ handle_redis_error(e, 'incr')
38
+ raise RedisConnectionError, "Failed to increment key: #{e.message}"
39
+ end
40
+
41
+ def get(key)
42
+ redis.with do |conn|
43
+ conn.get(key)
44
+ end
45
+ rescue ::Redis::BaseConnectionError => e
46
+ handle_redis_error(e, 'get')
47
+ nil # Fallback for reads
48
+ end
49
+
50
+ def health_check
51
+ redis.with do |conn|
52
+ conn.ping == 'PONG'
53
+ end
54
+ rescue ::Redis::BaseConnectionError
55
+ false
56
+ end
57
+
58
+ def with_redis(&block)
59
+ redis.with(&block)
60
+ rescue ::Redis::BaseConnectionError => e
61
+ handle_redis_error(e, 'with_redis')
62
+ raise ::RedisConnectionError, "Redis operation failed: #{e.message}"
63
+ end
64
+
65
+ # Clear cached Redis connection pool (useful for hot reloading in development)
66
+ def clear_redis_pool_cache!
67
+ @pool = nil
68
+ end
69
+
70
+ private
71
+
72
+ def lua_atomic_validate
73
+ <<~LUA
74
+ local key = KEYS[1]
75
+ local ttl = tonumber(ARGV[1])
76
+ local timestamp = tonumber(ARGV[2])
77
+ local expiration_time = tonumber(ARGV[3])
78
+ local current_time = tonumber(ARGV[4])
79
+
80
+ -- Check if token is expired
81
+ if expiration_time <= (current_time - timestamp) then
82
+ return 'stale'
83
+ end
84
+
85
+ -- Check if token was already used
86
+ local current = redis.call('GET', key)
87
+ if current and tonumber(current) > 0 then
88
+ return 'used'
89
+ end
90
+
91
+ -- Mark token as used
92
+ redis.call('INCRBY', key, 1)
93
+ redis.call('EXPIRE', key, ttl)
94
+
95
+ return 'ok'
96
+ LUA
97
+ end
98
+
99
+ def ttl_seconds
100
+ ::RobustServerSocket.configuration.token_expiration_time + 60
101
+ end
102
+
103
+ # Cache Redis connection pool at module level for the lifetime of the Rails process
104
+ # This avoids recreating the connection pool on every Redis operation
105
+ def redis
106
+ @pool ||= ::ConnectionPool::Wrapper.new(**pool_config) do
107
+ ::Redis.new(redis_config)
108
+ end
109
+ end
110
+
111
+ def pool_config
112
+ {
113
+ size: ENV.fetch('REDIS_POOL_SIZE', 25).to_i,
114
+ timeout: ENV.fetch('REDIS_POOL_TIMEOUT', 1).to_f
115
+ }
116
+ end
117
+
118
+ def redis_config
119
+ config = {
120
+ url: ::RobustServerSocket.configuration.redis_url,
121
+ reconnect_attempts: 3,
122
+ timeout: 1.0,
123
+ connect_timeout: 2.0
124
+ }
125
+
126
+ password = ::RobustServerSocket.configuration.redis_pass
127
+ config[:password] = password if password && !password.empty?
128
+
129
+ config
130
+ end
131
+
132
+ def handle_redis_error(error, operation)
133
+ warn "Redis operation '#{operation}' failed: #{error.class} - #{error.message}"
134
+ end
135
+ end
136
+ end
137
+ end
138
+ end
@@ -0,0 +1,41 @@
1
+ require 'openssl'
2
+
3
+ module RobustServerSocket
4
+ module SecureToken
5
+ BASE64_REGEXP = /\A[A-Za-z0-9+\/]*={0,2}\z/.freeze
6
+ InvalidToken = Class.new(StandardError)
7
+
8
+ module Decrypt
9
+ class << self
10
+ def call(token)
11
+ unless token.is_a?(String) && token.match?(BASE64_REGEXP)
12
+ raise InvalidToken, 'Invalid token format'
13
+ end
14
+
15
+ decoded_token = ::Base64.strict_decode64(token)
16
+
17
+ if decoded_token.bytesize > 1024
18
+ raise InvalidToken, 'Token too large'
19
+ end
20
+
21
+ private_key.private_decrypt(decoded_token, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING).force_encoding('UTF-8')
22
+ rescue ::OpenSSL::PKey::RSAError, ArgumentError
23
+ raise InvalidToken, 'Invalid token'
24
+ end
25
+
26
+ # Clear cached private key (useful for hot reloading in development)
27
+ def clear_private_key_cache!
28
+ @private_key = nil
29
+ end
30
+
31
+ private
32
+
33
+ # Cache RSA private key at module level for the lifetime of the Rails process
34
+ # This avoids recreating the RSA object on every token decryption
35
+ def private_key
36
+ @private_key ||= ::OpenSSL::PKey::RSA.new(RobustServerSocket.configuration.private_key)
37
+ end
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'robust_server_socket/configuration'
4
+
5
+ module RobustServerSocket
6
+ extend RobustServerSocket::Configuration
7
+
8
+ module_function
9
+
10
+ def load!
11
+ raise 'You must correctly configure RobustServerSocket first!' unless configured?
12
+
13
+ require 'openssl'
14
+ require 'base64'
15
+ require 'redis'
16
+ require 'connection_pool'
17
+
18
+ require_relative 'robust_server_socket/rate_limiter'
19
+ require_relative 'robust_server_socket/client_token'
20
+ require_relative 'robust_server_socket/private_message'
21
+ end
22
+ end
data/lib/version.rb ADDED
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RobustServerSocket
4
+ VERSION = '0.3.1'
5
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "./lib/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "robust_server_socket"
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"
14
+
15
+ # Specify which files should be added to the gem when it is released.
16
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
17
+ spec.files = Dir.chdir(__dir__) do
18
+ `git ls-files -z`.split("\x0").reject do |f|
19
+ (File.expand_path(f) == __FILE__) ||
20
+ f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor Gemfile])
21
+ end
22
+ end
23
+ spec.bindir = "exe"
24
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
25
+ spec.require_paths = ["lib"]
26
+ spec.add_dependency 'rspec'
27
+ spec.add_dependency 'rake'
28
+ spec.add_dependency 'redis'
29
+ spec.add_dependency 'hiredis'
30
+
31
+ # Uncomment to register a new dependency of your gem
32
+ # spec.add_dependency "example-gem", "~> 1.0"
33
+
34
+ # For more information and examples about making a new gem, check out our
35
+ # guide at: https://bundler.io/guides/creating_gem.html
36
+ end
metadata ADDED
@@ -0,0 +1,108 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: robust_server_socket
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.3.1
5
+ platform: ruby
6
+ authors:
7
+ - tee_zed
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: rspec
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: rake
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '0'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '0'
40
+ - !ruby/object:Gem::Dependency
41
+ name: redis
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '0'
47
+ type: :runtime
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: '0'
54
+ - !ruby/object:Gem::Dependency
55
+ name: hiredis
56
+ requirement: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: '0'
61
+ type: :runtime
62
+ prerelease: false
63
+ version_requirements: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: '0'
68
+ description: Robust Server Socket
69
+ email:
70
+ - tee0zed@gmail.com
71
+ executables: []
72
+ extensions: []
73
+ extra_rdoc_files: []
74
+ files:
75
+ - ".rspec"
76
+ - CODE_OF_CONDUCT.md
77
+ - LICENSE.txt
78
+ - README.md
79
+ - Rakefile
80
+ - lib/robust_server_socket.rb
81
+ - lib/robust_server_socket/client_token.rb
82
+ - lib/robust_server_socket/configuration.rb
83
+ - lib/robust_server_socket/rate_limiter.rb
84
+ - lib/robust_server_socket/secure_token/cacher.rb
85
+ - lib/robust_server_socket/secure_token/decrypt.rb
86
+ - lib/version.rb
87
+ - robust_server_socket.gemspec
88
+ licenses:
89
+ - MIT
90
+ metadata: {}
91
+ rdoc_options: []
92
+ require_paths:
93
+ - lib
94
+ required_ruby_version: !ruby/object:Gem::Requirement
95
+ requirements:
96
+ - - ">="
97
+ - !ruby/object:Gem::Version
98
+ version: 2.7.0
99
+ required_rubygems_version: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ requirements: []
105
+ rubygems_version: 3.6.9
106
+ specification_version: 4
107
+ summary: Robust Server Socket gem for RobustPro
108
+ test_files: []