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.
data/README.en.md CHANGED
@@ -17,14 +17,16 @@ When building microservice architecture, the server side faces:
17
17
  - **DDoS attacks**: Need to limit request frequency
18
18
  - **Boilerplate code**: Repetitive validation logic in every service
19
19
 
20
+ #### Even if infrastructure is behind a DMZ in a private network, there is still room for SSRF or OpenRedirect attacks
21
+
20
22
  ### The Solution
21
23
 
22
24
  RobustServerSocket provides:
23
25
 
24
- - **RSA decryption**: Token authenticity verification
26
+ - **Token decryption**: X25519 + AES-256-GCM authenticity check
25
27
  - **Client whitelist**: Only authorized services allowed
26
28
  - **Replay protection**: Blacklist of used tokens in Redis
27
- - **Rate limiting**: Per-client request limits
29
+ - **Rate limiting**: Sliding window per-client request limits
28
30
 
29
31
  ## HOW IT WORKS
30
32
 
@@ -37,7 +39,7 @@ Incoming request with Secure-Token
37
39
  ┌──────────────────────────────┐
38
40
  │ RobustServerSocket │
39
41
  │ │
40
- │ 1. RSA Decrypt │
42
+ │ 1. Open token (AES-GCM) │
41
43
  │ 2. Validate Format │
42
44
  │ 3. Check Client Whitelist │
43
45
  │ 4. Check Rate Limit │
@@ -53,19 +55,19 @@ Incoming request with Secure-Token
53
55
 
54
56
  ### Validation Flow
55
57
 
56
- 1. **Decryption**: Base64 decode → RSA decrypt with private key
57
- 2. **Parsing**: Extract `{client_name}_{timestamp}` from token
58
+ 1. **Decryption**: Base64 decode → X25519 + AES-256-GCM with the service private key
59
+ 2. **Parsing**: Extract `{client_name}_{timestamp_ms}` from token
58
60
  3. **Whitelist**: Verify client_name is in `allowed_services`
59
- 4. **Rate limit**: Check request count within window
61
+ 4. **Rate limit**: Sliding window — check request count within `rate_limit_window_seconds`
60
62
  5. **Replay check**: Verify token hasn't been used (Redis)
61
- 6. **Staleness**: Verify timestamp is current
63
+ 6. **Staleness**: Verify timestamp is current (with ±30s clock skew tolerance)
62
64
 
63
65
  ### Modular System
64
66
 
65
67
  Checks are enabled via `using_modules`:
66
68
  - `:client_auth_protection` — client whitelist
67
69
  - `:replay_attack_protection` — prevent token reuse
68
- - `:dos_attack_protection` — rate limiting
70
+ - `:rate_limit_protection` — sliding window rate limiting
69
71
 
70
72
  ## 📋 Table of Contents
71
73
 
@@ -80,48 +82,44 @@ Checks are enabled via `using_modules`:
80
82
  RobustServerSocket implements a multi-layered protection system for inter-service communications:
81
83
 
82
84
  ### 1. Cryptographic Protection
83
- - **RSA-2048 Encryption**: Uses RSA key pairs with minimum 2048-bit length
84
- - **Key Validation**: Automatic key size verification during configuration
85
- - **Asymmetric Encryption**: Private key on server, public keys on clients
86
-
87
- ### 2. Token Reuse Protection
88
- - **One-time Tokens**: Each token can only be used once
89
- - **Redis Blacklist**: Used tokens are automatically added to blacklist
90
- - **Atomic Verification**: Race conditions prevented via Redis Lua scripts
91
-
92
- ### 3. Time-based Restrictions
93
- - **Expiration Time**: Configurable token lifetime
94
- - **Automatic Expiration**: Tokens automatically become invalid after expiration
95
- - **Replay Attack Protection**: Old tokens cannot be reused
96
-
97
- ### 4. Access Control
98
- - **Client Whitelist**: Only authorized services can connect
85
+ - **Scheme**: `c.cipher`, default `:x25519`, `:x448` is built in. Client and server must pick the same one
86
+ - **X25519 / X448 + AES-256-GCM**: the token is sealed with an ephemeral key to the service's static key pair
87
+ - **Your own scheme**: `CipherRegistry.register(:name, object)` — an object with `open` and `read_private_key`
88
+ - **Key validation**: only a private key of the selected scheme is accepted; RSA is rejected
89
+
90
+ ### 2. Access Control
91
+ - **Client Whitelist**: Only authorized services can connect, when `:client_auth_protection` module is enabled
99
92
  - **Name-based Identification**: Each client must be explicitly listed in `allowed_services`
100
- - **Token Format Validation**: Strict token structure verification
101
93
 
102
- ### 5. Rate Limiting (optional)
103
- - **DDoS Protection**: Limit number of requests from each client
104
- - **Sliding Window**: Fair distribution of requests over time
105
- - **Fail-open Strategy**: If Redis is unavailable, requests are allowed (for reliability)
106
- - **Per-client Limits**: Individual counters for each client
94
+ ### 3. Replay Attack Protection
95
+ - **One-time Tokens**: Used tokens are added to a Redis blacklist, when `:replay_attack_protection` is enabled
96
+ - **Staleness Check**: Tokens automatically become invalid after `token_expiration_time`
97
+ - **Clock Skew Tolerance**: ±30 seconds (CLOCK_SKEW)
98
+ - **Blacklist TTL**: Computed automatically as `token_expiration_time + CLOCK_SKEW`
99
+
100
+ ### 4. Rate Limiting
101
+ - **Sliding Window**: When `:rate_limit_protection` is enabled — precise request counting without the burst effect of fixed windows
102
+ - **Fail-open Strategy**: If Redis is unavailable, requests are allowed through (for service reliability)
103
+ - **Per-client Isolation**: Counter is tracked individually per `client_name`
104
+
105
+ ### 5. SSL Stripping / MITM Protection
106
+ - **Enforce HTTPS on server**: All requests should be made over HTTPS to protect tokens from interception
107
+ - **Enabled on RobustClientSocket with `ssl_verify: true`**
107
108
 
108
109
  ### 6. Injection Protection
109
110
  - **Input Validation**: Type, length, and format verification of tokens
110
- - **Maximum Token Length**: 2048 character limit
111
+ - **Maximum Token Length**: 512 character limit
111
112
  - **Empty Value Checks**: Rejection of empty or malformed tokens
112
113
 
113
114
  ## 📦 Installation
114
115
 
115
- Add to Gemfile:
116
-
117
116
  ```ruby
118
117
  gem 'robust_server_socket'
119
118
  ```
120
119
 
121
- Then execute:
122
-
123
- ```bash
124
- bundle install
120
+ and on the client:
121
+ ```ruby
122
+ gem 'robust_client_socket'
125
123
  ```
126
124
 
127
125
  ## ⚙️ Configuration
@@ -130,125 +128,122 @@ Create file `config/initializers/robust_server_socket.rb`:
130
128
 
131
129
  ```ruby
132
130
  RobustServerSocket.configure do |c|
133
- # REQUIRED PARAMETERS
134
-
135
- # Service private key (RSA-2048 or higher)
136
- # IMPORTANT: Store in environment variables, DO NOT commit to git!
131
+ c.using_modules = %i[
132
+ client_auth_protection
133
+ replay_attack_protection
134
+ rate_limit_protection
135
+ ]
136
+
137
+ # Service private key (X25519 PEM, or X448 when cipher is :x448)
137
138
  c.private_key = ENV['ROBUST_SERVER_PRIVATE_KEY']
138
-
139
- # Token lifetime in seconds
140
- # Recommendation: 1-3 seconds for production (time from client request to server)
141
- c.token_expiration_time = 3
142
-
139
+ c.cipher = :x25519
140
+
141
+ # Token lifetime in seconds (must match TTL on client side)
142
+ c.token_expiration_time = 10
143
+
143
144
  # List of allowed services (whitelist)
144
- # Must match names in client keychain
145
+ # Must match service_name in RobustClientSocket
145
146
  c.allowed_services = %w[core payments notifications]
146
-
147
- # Redis for storing used tokens
147
+
148
+ # Redis for replay_attack_protection and rate_limit_protection
148
149
  c.redis_url = ENV.fetch('REDIS_URL', 'redis://localhost:6379/0')
149
- c.redis_pass = ENV['REDIS_PASSWORD'] # can be nil for local development
150
+ c.redis_pass = ENV['REDIS_PASSWORD']
150
151
 
151
- # Maximum requests per time window (default: 100)
152
- c.rate_limit_max_requests = 100
153
-
154
- # Time window size in seconds (default: 60)
155
- c.rate_limit_window_seconds = 60
152
+ # rate_limit_protection
153
+ c.rate_limit_max_requests = 100 # max requests per window (default: 100)
154
+ c.rate_limit_window_seconds = 60 # window size in seconds (default: 60)
156
155
  end
157
156
 
158
- # Load configuration with validation
159
157
  RobustServerSocket.load!
160
158
  ```
161
159
 
160
+ ### Configuration Options
161
+
162
+ | Parameter | Type | Required | Default | Description |
163
+ |-----------------------------|---------|----------|-------------------------------------------------------------------------------------|-------------------------------------------------|
164
+ | `private_key` | String | ✅ | — | Private key of the selected scheme (PEM) |
165
+ | `cipher` | Symbol | ❌ | `:x25519` | Token scheme: `:x25519`, `:x448`, or your own |
166
+ | `token_expiration_time` | Integer | ✅ | 10 | Token lifetime in seconds |
167
+ | `allowed_services` | Array | ✅ | — | Allowed services whitelist |
168
+ | `redis_url` | String | ✅ | — | Redis connection URL |
169
+ | `redis_pass` | String | ❌ | nil | Redis password |
170
+ | `using_modules` | Array | ❌ | `[:client_auth_protection, :rate_limit_protection, :replay_attack_protection]` | Enabled modules |
171
+ | `rate_limit_max_requests` | Integer | ❌ | 100 | Max requests per window |
172
+ | `rate_limit_window_seconds` | Integer | ❌ | 60 | Window size in seconds |
173
+
174
+ > `store_used_token_time` is no longer configurable — computed automatically as `token_expiration_time + 30` (CLOCK_SKEW).
175
+
176
+ ### Compatibility with RobustClientSocket
177
+
178
+ The token contains a timestamp in **milliseconds**. RobustClientSocket starting from version 0.5.3 must generate:
179
+
180
+ ```ruby
181
+ Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond)
182
+ ```
183
+
184
+ The legacy `Time.now.utc.to_i` (seconds) will cause all tokens to be rejected as `stale`.
185
+
162
186
  ## 🚀 Usage
163
187
 
164
188
  ### Basic Authorization
165
189
 
166
190
  ```ruby
167
- # In controller or middleware
168
191
  class ApiController < ApplicationController
169
192
  before_action :authenticate_service!
170
-
193
+
171
194
  private
172
-
195
+
173
196
  def authenticate_service!
174
- # Header configured in RobustClientSocket (SECURE-TOKEN default)
175
197
  token = request.headers['SECURE-TOKEN']&.sub(/^Bearer /, '')
176
-
177
- @current_service = RobustServerSocket::ClientToken.validate!(token) # bang method (raises errors)
198
+ @current_service = RobustServerSocket::ClientToken.validate!(token)
178
199
  rescue RobustServerSocket::ClientToken::InvalidToken
179
200
  render json: { error: 'Invalid token' }, status: :unauthorized
180
- rescue RobustServerSocket::ClientToken::UnauthorizedClient
201
+ rescue RobustServerSocket::Modules::ClientAuthProtection::UnauthorizedClient
181
202
  render json: { error: 'Unauthorized service' }, status: :forbidden
182
- rescue RobustServerSocket::ClientToken::UsedToken
203
+ rescue RobustServerSocket::Modules::ReplayAttackProtection::UsedToken
183
204
  render json: { error: 'Token already used' }, status: :unauthorized
184
- rescue RobustServerSocket::ClientToken::StaleToken
205
+ rescue RobustServerSocket::Modules::ReplayAttackProtection::StaleToken
185
206
  render json: { error: 'Token expired' }, status: :unauthorized
186
207
  rescue RobustServerSocket::RateLimiter::RateLimitExceeded => e
187
208
  render json: { error: e.message }, status: :too_many_requests
188
209
  end
189
-
190
- def authenticate_service
191
- token = request.headers['SECURE-TOKEN']&.sub(/^Bearer /, '')
192
- @current_service = RobustServerSocket::ClientToken.new(token)
193
-
194
- if @current_service.valid? # doesn't raise errors
195
- # Token is valid
196
- else
197
- # Token is invalid
198
- render json: { error: 'Unauthorized' }, status: :unauthorized
199
- end
200
- end
201
210
  end
202
211
  ```
203
212
 
204
- ### Advanced Usage
213
+ ### valid? (non-raising)
205
214
 
206
215
  ```ruby
207
- # Create token object
208
- token_string = request.headers['SECURE-TOKEN']&.sub(/^Bearer /, '')
209
- client_token = RobustServerSocket::ClientToken.new(token_string)
216
+ token = request.headers['SECURE-TOKEN']&.sub(/^Bearer /, '')
217
+ client_token = RobustServerSocket::ClientToken.new(token)
210
218
 
211
- # Check validity (returns true/false)
212
219
  if client_token.valid?
213
- # Get client name
214
220
  client_name = client_token.client
215
- puts "Authorized client: #{client_name}"
216
221
  else
217
- # Token is invalid
218
222
  render json: { error: 'Unauthorized' }, status: :unauthorized
219
223
  end
220
-
221
- # Quick validation with exceptions (recommended)
222
- begin
223
- service_token = RobustServerSocket::ClientToken.validate!(token_string)
224
- client_name = service_token.client
225
- rescue => e
226
- # Handle specific errors
227
- end
228
224
  ```
229
225
 
230
226
  ## ❌ Error Handling
231
227
 
232
228
  ### Exception Types
233
229
 
234
- | Exception | Reason | HTTP Status | Action |
235
- |-----------|--------|-------------|--------|
236
- | `InvalidToken` | Token cannot be decrypted or has invalid format | 401 | Check token and key correctness |
237
- | `UnauthorizedClient` | Client not in whitelist | 403 | Add client to `allowed_services` |
238
- | `UsedToken` | Token has already been used | 401 | Client must request new token |
239
- | `StaleToken` | Token has expired | 401 | Client must request new token |
240
- | `RateLimitExceeded` | Rate limit exceeded | 429 | Client should wait or retry later |
230
+ | Exception | Reason | HTTP Status |
231
+ |------------------------------------------------------------|-------------------------------------------|-------------|
232
+ | `ClientToken::InvalidToken` | Token cannot be decrypted or wrong format | 401 |
233
+ | `Modules::ClientAuthProtection::UnauthorizedClient` | Client not in whitelist | 403 |
234
+ | `Modules::ReplayAttackProtection::UsedToken` | Token has already been used | 401 |
235
+ | `Modules::ReplayAttackProtection::StaleToken` | Token expired or from the future (>30s) | 401 |
236
+ | `RateLimiter::RateLimitExceeded` | Rate limit exceeded | 429 |
241
237
 
242
238
  ### Centralized Error Handling
243
239
 
244
240
  ```ruby
245
- # In ApplicationController
246
241
  rescue_from RobustServerSocket::ClientToken::InvalidToken,
247
- RobustServerSocket::ClientToken::UsedToken,
248
- RobustServerSocket::ClientToken::StaleToken,
242
+ RobustServerSocket::Modules::ReplayAttackProtection::UsedToken,
243
+ RobustServerSocket::Modules::ReplayAttackProtection::StaleToken,
249
244
  with: :unauthorized_response
250
245
 
251
- rescue_from RobustServerSocket::ClientToken::UnauthorizedClient,
246
+ rescue_from RobustServerSocket::Modules::ClientAuthProtection::UnauthorizedClient,
252
247
  with: :forbidden_response
253
248
 
254
249
  rescue_from RobustServerSocket::RateLimiter::RateLimitExceeded,
@@ -257,80 +252,24 @@ rescue_from RobustServerSocket::RateLimiter::RateLimitExceeded,
257
252
  private
258
253
 
259
254
  def unauthorized_response(exception)
260
- render json: {
261
- error: 'Authentication failed',
262
- message: exception.message,
263
- type: exception.class.name
264
- }, status: :unauthorized
255
+ render json: { error: 'Authentication failed', message: exception.message }, status: :unauthorized
265
256
  end
266
257
 
267
258
  def forbidden_response(exception)
268
- render json: {
269
- error: 'Access denied',
270
- message: exception.message,
271
- type: exception.class.name
272
- }, status: :forbidden
259
+ render json: { error: 'Access denied', message: exception.message }, status: :forbidden
273
260
  end
274
261
 
275
262
  def rate_limit_response(exception)
276
263
  render json: {
277
264
  error: 'Too many requests',
278
265
  message: exception.message,
279
- type: exception.class.name,
280
266
  retry_after: RobustServerSocket.configuration.rate_limit_window_seconds
281
267
  }, status: :too_many_requests
282
268
  end
283
269
  ```
284
270
 
285
- ### 2. Redis Configuration
286
-
287
- **✅ DO:**
288
- ```ruby
289
- # Use separate namespace for each environment
290
- c.redis_url = ENV.fetch('REDIS_URL', 'redis://localhost:6379/0')
291
-
292
- # Configure connection pool in production
293
- # In config/initializers/redis.rb
294
- Redis.current = ConnectionPool.new(size: 5, timeout: 5) do
295
- Redis.new(url: ENV['REDIS_URL'], password: ENV['REDIS_PASSWORD'])
296
- end
297
-
298
- # Monitor Redis status
299
- # Use Redis Sentinel or Cluster for high availability
300
- ```
301
-
302
- **❌ DON'T:**
303
- ```ruby
304
- # DON'T use same Redis DB for all environments, use separate Redis DB
305
- # DON'T ignore Redis errors (rate limiter is already fail-open, but log them)
306
- ```
307
-
308
- ### 5. Service Whitelist
309
-
310
- ```ruby
311
- # Explicitly specify only necessary services
312
- c.allowed_services = %w[core payments] # ✅
313
-
314
- # DON'T use wildcards or regular expressions
315
- c.allowed_services = %w[*] # ❌ DANGEROUS!
316
-
317
- # Synchronize with client keychain
318
- # Server (robust_server_socket):
319
- c.allowed_services = %w[core]
320
-
321
- # Client (robust_client_socket):
322
- c.keychain = {
323
- core: { # ← Must match
324
- base_uri: 'https://core.example.com',
325
- public_key: '-----BEGIN PUBLIC KEY-----...'
326
- }
327
- }
328
- ```
329
-
330
271
  ## 🤝 Integration with RobustClientSocket
331
272
 
332
- For full functionality, configure the client side:
333
-
334
273
  ```ruby
335
274
  # On client (RobustClientSocket)
336
275
  RobustClientSocket.configure do |c|
@@ -338,271 +277,50 @@ RobustClientSocket.configure do |c|
338
277
  c.keychain = {
339
278
  payments: {
340
279
  base_uri: 'https://payments.example.com',
341
- public_key: '-----BEGIN PUBLIC KEY-----...' # Public key of payments server
280
+ public_key: '-----BEGIN PUBLIC KEY-----...'
342
281
  }
343
282
  }
344
283
  end
345
284
 
346
285
  # On server (RobustServerSocket)
347
286
  RobustServerSocket.configure do |c|
348
- c.allowed_services = %w[core] # ← Matches client's service_name
349
- c.private_key = '-----BEGIN PRIVATE KEY-----...' # Private pair to public_key
287
+ c.allowed_services = %w[core]
288
+ c.private_key = '-----BEGIN PRIVATE KEY-----...'
350
289
  end
351
290
  ```
352
291
 
353
- ## 📚 Additional Resources
354
-
355
- - [RobustClientSocket documentation](https://github.com/tee0zed/robust_client_socket)
356
- - [RSA encryption best practices](https://www.openssl.org/docs/)
357
- - [Redis security guide](https://redis.io/topics/security)
358
-
359
- ## 📝 License
292
+ ## 📊 Performance
360
293
 
361
- See [MIT-LICENSE](MIT-LICENSE) file
362
-
363
- ## 🐛 Bugs and Suggestions
364
-
365
- Report issues through your repository's issue tracker.
366
-
367
-
368
- #### Test: 1000 Requests with Token Validation
294
+ ### Benchmark: 1000 Requests with Token Validation
369
295
 
370
296
  **Without RobustServerSocket (plain HTTP controller):**
371
- ```ruby
372
- Benchmark.measure do
373
- 1000.times do
374
- # Regular request without authorization
375
- get '/api/v1/partners/719a68e4-3457-45dd-8d7f-73f1d367b87a/merchants'
376
- end
377
- end
378
- ```
379
-
380
- **Results (approximate):**
381
- - **Real time**: ~2.5 seconds
382
- - No token verification
383
- - No RSA decryption
384
- - No Redis checks
385
-
386
- ---
297
+ - Real time: ~2.5 seconds
298
+ - No token verification, no AES-GCM open, no Redis checks
387
299
 
388
300
  **With RobustServerSocket (full protection):**
389
- ```ruby
390
- Benchmark.measure do
391
- 1000.times do
392
- # Request with RobustClientSocket (RSA + tokens)
393
- RobustClientSocket::CoreApi.get('/api/v1/partners/719a68e4-3457-45dd-8d7f-73f1d367b87a/merchants')
394
- end
395
- end
396
- ```
397
-
398
- **Results:**
399
- - **Real time**: 2.77 seconds
400
- - **User CPU**: 0.23 seconds
401
- - **System CPU**: 0.54 seconds
402
- - **Total CPU**: 0.77 seconds
403
-
404
- ### 📊 Security Overhead Analysis
405
-
406
- | Operation | Time | % of Request |
407
- |-----------|------|-------------|
408
- | **RSA Decryption** | ~0.1-0.2ms | 3-7% |
409
- | **Redis Token Check** | ~0.05-0.1ms | 2-3% |
410
- | **Rate Limiting** | ~0.02-0.05ms | 1% |
411
- | **Whitelist Validation** | <0.01ms | <1% |
412
- | **Total Overhead** | **~0.2-0.4ms** | **~10-15%** |
413
-
414
- ### 🎯 Key Findings
415
-
416
- 1. **Minimal overhead (~0.3ms per request)**
417
- - RSA-2048 decryption: ~0.15ms
418
- - Redis operations: ~0.08ms
419
- - Rate limiting: ~0.03ms
420
-
421
- 2. **Scales linearly**
422
- - 100 req/s = +30ms overhead
423
- - 1000 req/s = +300ms overhead
424
- - Acceptable for most applications
425
-
426
- 3. **Redis is main bottleneck**
427
- - Use Redis Sentinel/Cluster
428
- - Connection pooling is critical
429
- - Fail-open strategy for reliability
430
-
431
- ### 💡 Performance Optimization
432
-
433
- **1. Redis Connection Pool:**
434
-
435
- ```ruby
436
- # config/initializers/redis.rb
437
- require 'connection_pool'
438
-
439
- REDIS_POOL = ConnectionPool.new(size: 25, timeout: 5) do
440
- Redis.new(
441
- url: ENV['REDIS_URL'],
442
- password: ENV['REDIS_PASSWORD'],
443
- reconnect_attempts: 3,
444
- reconnect_delay: 0.5,
445
- reconnect_delay_max: 5.0
446
- )
447
- end
448
-
449
- # In RobustServerSocket::Cacher
450
- def self.with_redis
451
- REDIS_POOL.with do |redis|
452
- yield redis
453
- end
454
- end
455
- ```
456
-
457
- **2. Public Key Caching:**
458
-
459
- ```ruby
460
- # Keys are already cached at load!, but can be optimized
461
- class RobustServerSocket::ClientToken
462
- # Keys are loaded once at application startup
463
- # No additional optimization needed
464
- end
465
- ```
466
-
467
- **3. Rate Limiting Optimization:**
468
-
469
- ```ruby
470
- RobustServerSocket.configure do |c|
471
- # For high-load systems
472
- c.rate_limit_max_requests = 1000 # Increase limit
473
- c.rate_limit_window_seconds = 60
474
-
475
- # For low-load systems
476
- c.rate_limit_max_requests = 100
477
- c.rate_limit_window_seconds = 60
478
- end
479
- ```
480
-
481
- **4. Token Expiration Optimization:**
482
-
483
- ```ruby
484
- # Short lifetime = more requests for new tokens
485
- c.token_expiration_time = 10.minutes # ❌ High traffic
486
-
487
- # Optimal time for inter-service calls
488
- c.token_expiration_time = 3 # ✅ 3 seconds is enough
489
- ```
490
-
491
- ### 🔬 Performance Monitoring
492
-
493
- **Metrics to Track:**
301
+ - Real time: ~2.77 seconds
302
+ - User CPU: 0.23s, System CPU: 0.54s
494
303
 
495
- ```ruby
496
- class ApiController < ApplicationController
497
- around_action :track_auth_performance
498
-
499
- private
500
-
501
- def track_auth_performance
502
- start = Time.now
503
-
504
- begin
505
- yield
506
- ensure
507
- duration = ((Time.now - start) * 1000).round(2)
508
-
509
- # Total request time
510
- Metrics.timing('request.duration', duration, tags: [
511
- "controller:#{controller_name}",
512
- "action:#{action_name}"
513
- ])
514
-
515
- # Authentication attempts
516
- if @current_service
517
- Metrics.increment('auth.success', tags: ["service:#{@current_service.client}"])
518
- else
519
- Metrics.increment('auth.failure')
520
- end
521
- end
522
- end
523
- end
524
-
525
- # Specific metrics for RobustServerSocket
526
- module RobustServerSocket
527
- class ClientToken
528
- def self.validate_with_metrics!(token)
529
- start = Time.now
530
- result = validate!(token)
531
- duration = ((Time.now - start) * 1000).round(2)
532
-
533
- Metrics.timing('robust_server.validation.duration', duration)
534
- result
535
- rescue StandardError => e
536
- Metrics.increment('robust_server.validation.error', tags: ["error:#{e.class.name}"])
537
- raise
538
- end
539
- end
540
- end
541
- ```
542
-
543
- ### 📈 Performance at Different Loads
544
-
545
- | Req/s | Without Protection | With RobustServerSocket | Overhead | Acceptable |
546
- |-------|-------------------|------------------------|----------|-----------|
547
- | 10 | 100ms | 103ms | 3ms | ✅ Excellent |
548
- | 100 | 1s | 1.03s | 30ms | ✅ Excellent |
549
- | 500 | 5s | 5.15s | 150ms | ✅ Good |
550
- | 1,000 | 10s | 10.3s | 300ms | ✅ Acceptable |
551
- | 5,000 | 50s | 51.5s | 1.5s | ⚠️ Redis scaling needed |
552
- | 10,000 | 100s | 103s | 3s | ⚠️ Need Redis Cluster |
553
-
554
- **Conclusion:** Up to 1000 req/s - excellent performance. Higher loads require Redis scaling.
555
-
556
- ### 🚀 Production Recommendations
557
-
558
- **For high-load systems (>1000 req/s):**
559
-
560
- 1. **Redis Cluster** - distributed load
561
- 2. **Connection Pool** - minimum 25-50 connections
562
- 3. **Monitor Redis** - latency, memory, connections
563
- 4. **Fail-over Strategy** - Redis Sentinel
564
- 5. **CDN for static** - reduce overall load
565
-
566
- **For medium load (100-1000 req/s):**
567
-
568
- 1. **Standalone Redis** with persistence
569
- 2. **Connection Pool** - 10-25 connections
570
- 3. **Basic monitoring**
571
- 4. **Rate limiting** - spike protection
304
+ ### Security Overhead Analysis
572
305
 
573
- **For low load (<100 req/s):**
306
+ | Operation | Time | % of Request |
307
+ |------------------------|-------------|-------------|
308
+ | AES-256-GCM open | ~0.05ms | 1–3% |
309
+ | Redis Token Check | ~0.05–0.1ms | 2–3% |
310
+ | Rate Limiting | ~0.02–0.05ms| 1% |
311
+ | Whitelist Validation | <0.01ms | <1% |
312
+ | **Total Overhead** | **~0.2–0.4ms** | **~10–15%** |
574
313
 
575
- 1. **Simple Redis** setup
576
- 2. **Default connection pool** (5)
577
- 3. **Standard configuration**
314
+ Up to 1000 req/s — excellent performance. Higher loads require Redis Sentinel/Cluster.
578
315
 
579
- ## 🤝 Integration with RobustClientSocket
580
-
581
- For full functionality, configure the client side:
316
+ ## 🗺️ TODO
582
317
 
583
- ```ruby
584
- # On client (RobustClientSocket)
585
- RobustClientSocket.configure do |c|
586
- c.service_name = 'core' # ← Must be in server's allowed_services
587
- c.keychain = {
588
- payments: {
589
- base_uri: 'https://payments.example.com',
590
- public_key: '-----BEGIN PUBLIC KEY-----...' # Public key of payments server
591
- }
592
- }
593
- end
594
-
595
- # On server (RobustServerSocket)
596
- RobustServerSocket.configure do |c|
597
- c.allowed_services = %w[core] # ← Matches client's service_name
598
- c.private_key = '-----BEGIN PRIVATE KEY-----...' # Private pair to public_key
599
- end
600
- ```
318
+ - [ ] **Per-client rate limit keys** — configurable individual limits per `client_name` instead of a single global limit
601
319
 
602
320
  ## 📚 Additional Resources
603
321
 
604
- - [RobustClientSocket documentation](../robust_client_socket/README.md)
605
- - [RSA encryption best practices](https://www.openssl.org/docs/)
322
+ - [RobustClientSocket](https://github.com/tee0zed/robust_client_socket)
323
+ - [X25519](https://www.rfc-editor.org/rfc/rfc7748) and [AES-GCM](https://www.rfc-editor.org/rfc/rfc5116)
606
324
  - [Redis security guide](https://redis.io/topics/security)
607
325
 
608
326
  ## 📝 License
@@ -611,4 +329,4 @@ See [MIT-LICENSE](MIT-LICENSE) file
611
329
 
612
330
  ## 🐛 Bugs and Suggestions
613
331
 
614
- Report issues to my telegram @cruel_mango or to email tee0zed@gmail.com
332
+ Report issues via GitHub issues, or directly at Telegram @cruel_mango or email tee0zed@gmail.com