robust_client_socket 0.5.2 → 0.7.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 ADDED
@@ -0,0 +1,496 @@
1
+ # RobustClientSocket
2
+
3
+ ⚠️ Not Production Tested (yet)
4
+
5
+ `Not vibecoded`
6
+
7
+ HTTP client for secure inter-service communications with automatic authorization token generation.
8
+
9
+ ## WHY
10
+
11
+ ### The Problem
12
+
13
+ When building microservice communication, the following challenges arise:
14
+
15
+ - **Lack of authentication**: HTTP requests between services are unprotected
16
+ - **Replay attacks**: Intercepted requests can be reused maliciously
17
+ - **Manual key management**: Complexity of handling an X25519 key for each service
18
+ - **Boilerplate code**: Repetitive code for encryption and request sending
19
+
20
+ ### The Solution
21
+
22
+ RobustClientSocket provides:
23
+
24
+ - **Automatic tokenization**: Each request receives a unique encrypted token
25
+ - **Token encryption**: X25519 + AES-256-GCM with key validation
26
+ - **Keychain management**: Auto-generation of HTTP clients for each service
27
+ - **Replay attack protection**: Timestamp in every token
28
+
29
+ ## HOW IT WORKS
30
+
31
+ ### Architecture
32
+
33
+ ```
34
+ ┌───────────────────┐ ┌───────────────────┐
35
+ │ Your Service │ │ Target Service │
36
+ │ │ │ (RobustServer) │
37
+ └─────────┬─────────┘ └─────────┬─────────┘
38
+ │ │
39
+ v v
40
+ ┌───────────────────┐ ┌───────────────────┐
41
+ │ RobustClientSocket│ │ RobustServerSocket│
42
+ │ │ │ │
43
+ │ 1. Generate token │────>│ 1. Decrypt token │
44
+ │ 2. Seal token │ │ 2. Validate │
45
+ │ 3. Send request │ │ 3. Check limits │
46
+ └───────────────────┘ └───────────────────┘
47
+ ```
48
+
49
+ ### Request Flow
50
+
51
+ 1. **Token formation**: `{client_name}_{timestamp}`
52
+ 2. **Encryption**: Token is sealed to the target service's X25519 public key (ephemeral X25519 + AES-256-GCM)
53
+ 3. **Base64 encoding**: For HTTP header transmission
54
+ 4. **Request sending**: Request with `Secure-Token` header
55
+ 5. **Validation**: Server decrypts and validates the token
56
+
57
+ ### Token Structure
58
+
59
+ ```
60
+ Base64(ephemeral_public_der || iv || tag || AES-256-GCM("{client_name}_{unix_timestamp_ms}"))
61
+
62
+ The AES key is HKDF-SHA256 over the X25519 shared secret.
63
+ ```
64
+
65
+ ## 📋 Table of Contents
66
+
67
+ - [Security Features](#security-features)
68
+ - [Installation](#installation)
69
+ - [Configuration](#configuration)
70
+ - [Usage](#usage)
71
+ - [HTTP Methods](#http-methods)
72
+ - [Error Handling](#error-handling)
73
+ - [SSL/TLS Settings](#ssltls-settings)
74
+
75
+ ## 🔒 Security Features
76
+
77
+ RobustClientSocket provides secure communication between microservices:
78
+
79
+ ### 1. Automatic Tokenization
80
+ - **On-the-fly Token Generation**: Each request automatically gets a new token
81
+ - **Timestamps**: Tokens contain UTC timestamp for replay attack protection
82
+ - **One-time Tokens**: Each request uses a unique token
83
+
84
+ ### 2. Token encryption
85
+ - **Scheme**: `c.cipher`, default `:x25519`, `:x448` is built in. A per-service `cipher:` overrides it
86
+ - **X25519 / X448**: a fresh ephemeral key per token; the service keeps one static key pair of the same scheme
87
+ - **AES-256-GCM**: authenticated encryption, a tampered token is rejected
88
+ - **Your own scheme**: `CipherRegistry.register(:name, object)` — an object with `seal` and `read_public_key`
89
+ - **Key validation**: the key must match the scheme. RSA and a private key are rejected
90
+
91
+ ### 3. TLS/SSL Protection
92
+ - **TLS 1.2+**: Modern encryption protocols
93
+ - **Certificate Verification**: VERIFY_PEER mode for production
94
+ - **Configurable Cipher Suites**: ECDHE support for forward secrecy
95
+ - **HTTPS Enforcement**: Mandatory HTTPS usage in production
96
+
97
+ ### 4. Header Protection
98
+ - **Custom Headers**: Configurable header name for token
99
+ - **User-Agent Identification**: Client versioning
100
+ - **Content-Type Control**: Automatic headers for JSON
101
+
102
+ ### 5. Timeout Attack Protection
103
+ - **Connection Timeout**: Configurable connection timeout (default: 5s)
104
+ - **Request Timeout**: Configurable request timeout (default: 10s)
105
+ - **Hang Protection**: Automatic interruption of long requests
106
+
107
+ ### 6. Multi-service Architecture
108
+ - **Keychain Management**: Separate keys for each service
109
+ - **Automatic Client Generation**: Dynamic class creation for services
110
+ - **Configuration Isolation**: Independent settings for each service
111
+
112
+ ## 📦 Installation
113
+
114
+ Add to Gemfile:
115
+
116
+ ```ruby
117
+ gem 'robust_client_socket'
118
+ ```
119
+
120
+ Then execute:
121
+
122
+ ```bash
123
+ bundle install
124
+ ```
125
+
126
+ ## ⚙️ Configuration
127
+
128
+ Create file `config/initializers/robust_client_socket.rb`:
129
+
130
+ ```ruby
131
+ RobustClientSocket.configure do |c|
132
+ # REQUIRED: Current service (client) name
133
+ # Must match allowed_services on server
134
+ c.client_name = 'core'
135
+
136
+ # OPTIONAL: token scheme. Default :x25519, :x448 is built in.
137
+ # Your own: CipherRegistry.register(:name, object) with seal and read_public_key.
138
+ c.cipher = :x25519
139
+
140
+ # OPTIONAL: Header name for token (default: 'Secure-Token')
141
+ c.header_name = 'Secure-Token'
142
+
143
+ # KEYCHAIN: Configuration for each target service
144
+
145
+ # Basic configuration (without SSL validation)
146
+ c.payments = {
147
+ base_uri: 'http://localhost:3001',
148
+ public_key: ENV['PAYMENTS_PUBLIC_KEY']
149
+ }
150
+
151
+ # Production configuration with SSL
152
+ c.notifications = {
153
+ base_uri: 'https://notifications.example.com',
154
+ public_key: ENV['NOTIFICATIONS_PUBLIC_KEY'],
155
+ ssl_verify: true, # Enable SSL certificate verification
156
+ timeout: 15, # Request timeout (seconds)
157
+ open_timeout: 5 # Connection timeout (seconds)
158
+ }
159
+
160
+ # Configuration with custom cipher suites
161
+ c.core = {
162
+ base_uri: 'https://core.example.com',
163
+ public_key: ENV['CORE_PUBLIC_KEY'],
164
+ ssl_verify: true,
165
+ ciphers: %w[
166
+ ECDHE-ECDSA-AES128-GCM-SHA256
167
+ ECDHE-ECDSA-AES256-GCM-SHA384
168
+ ECDHE-ECDSA-CHACHA20-POLY1305
169
+ ]
170
+ }
171
+ end
172
+
173
+ # Load configuration and create clients
174
+ RobustClientSocket.load!
175
+ ```
176
+
177
+ ### Service Configuration Options
178
+
179
+ | Parameter | Type | Required | Default | Description |
180
+ |----------|-----|--------------|---------|----------|
181
+ | `base_uri` | String | ✅ | - | Target service URL |
182
+ | `public_key` | String | ✅ | - | Public key of the selected scheme (PEM). Default X25519 |
183
+ | `cipher` | Symbol | ❌ | `:x25519` | Token scheme: `:x25519`, `:x448`, or a registered one |
184
+ | `ssl_verify` | Boolean | ❌ | false | Enable SSL certificate verification |
185
+ | `timeout` | Integer | ❌ | 10 | Request timeout (seconds) |
186
+ | `open_timeout` | Integer | ❌ | 5 | Connection timeout (seconds) |
187
+ | `ciphers` | Array/String | ❌ | See below | TLS cipher suites |
188
+
189
+ **Default cipher suites:**
190
+ ```
191
+ ECDHE-ECDSA-AES128-GCM-SHA256
192
+ ECDHE-ECDSA-AES256-GCM-SHA384
193
+ ECDHE-ECDSA-CHACHA20-POLY1305
194
+ ```
195
+
196
+ ## 🚀 Usage
197
+
198
+ ### Automatic Client Generation
199
+
200
+ After `RobustClientSocket.load!` classes are automatically created for each represented service:
201
+
202
+ ```ruby
203
+ # Configuration
204
+ c.payments = { base_uri: '...', public_key: '...' }
205
+ c.notifications = { base_uri: '...', public_key: '...' }
206
+ c.user_management = { base_uri: '...', public_key: '...' }
207
+
208
+ # After load! classes are available:
209
+ RobustClientSocket::Payments # payments -> Payments
210
+ RobustClientSocket::Notifications # notifications -> Notifications
211
+ RobustClientSocket::UserManagement # user_management -> UserManagement
212
+ ```
213
+
214
+ ### Basic Usage
215
+
216
+ ```ruby
217
+ # GET request
218
+ response = RobustClientSocket::Payments.get('/api/v1/transactions')
219
+
220
+ if response.success?
221
+ transactions = response.parsed_response
222
+ puts "Transactions received: #{transactions.count}"
223
+ else
224
+ puts "Error: #{response.code} - #{response.message}"
225
+ end
226
+
227
+ # POST request with body
228
+ response = RobustClientSocket::Notifications.post(
229
+ '/api/v1/send',
230
+ body: {
231
+ user_id: 123,
232
+ message: 'Hello World',
233
+ type: 'email'
234
+ }.to_json
235
+ )
236
+
237
+ # PUT request
238
+ response = RobustClientSocket::UserManagement.put(
239
+ '/api/v1/users/123',
240
+ body: { name: 'John Doe' }.to_json
241
+ )
242
+
243
+ # DELETE request
244
+ response = RobustClientSocket::Payments.delete('/api/v1/transactions/456')
245
+
246
+ # PATCH request
247
+ response = RobustClientSocket::UserManagement.patch(
248
+ '/api/v1/users/123',
249
+ body: { status: 'active' }.to_json
250
+ )
251
+ ```
252
+
253
+ ### Query Parameters
254
+
255
+ ```ruby
256
+ # GET with query parameters
257
+ response = RobustClientSocket::Payments.get(
258
+ '/api/v1/transactions',
259
+ query: {
260
+ status: 'completed',
261
+ date_from: '2024-01-01',
262
+ limit: 100
263
+ }
264
+ )
265
+
266
+ # Automatically converted to:
267
+ # /api/v1/transactions?status=completed&date_from=2024-01-01&limit=100
268
+ ```
269
+
270
+ ### Custom Headers
271
+
272
+ ```ruby
273
+ # Adding additional headers
274
+ response = RobustClientSocket::Payments.get(
275
+ '/api/v1/transactions',
276
+ headers: {
277
+ 'X-Request-ID' => SecureRandom.uuid,
278
+ 'X-User-ID' => current_user.id.to_s
279
+ }
280
+ )
281
+
282
+ # Secure-Token header is added automatically!
283
+ ```
284
+
285
+ ## 🌐 HTTP Methods
286
+
287
+ All standard HTTPpartry methods:
288
+
289
+ ### GET
290
+ ```ruby
291
+ RobustClientSocket::ServiceName.get(path, options = {})
292
+ ```
293
+
294
+ ### POST
295
+ ```ruby
296
+ RobustClientSocket::ServiceName.post(path, options = {})
297
+ ```
298
+
299
+ ### PUT
300
+ ```ruby
301
+ RobustClientSocket::ServiceName.put(path, options = {})
302
+ ```
303
+
304
+ ### DELETE
305
+ ```ruby
306
+ RobustClientSocket::ServiceName.delete(path, options = {})
307
+ ```
308
+
309
+ ### PATCH
310
+ ```ruby
311
+ RobustClientSocket::ServiceName.patch(path, options = {})
312
+ ```
313
+
314
+ ### HEAD
315
+ ```ruby
316
+ RobustClientSocket::ServiceName.head(path, options = {})
317
+ ```
318
+
319
+ ### OPTIONS
320
+ ```ruby
321
+ RobustClientSocket::ServiceName.options(path, options = {})
322
+ ```
323
+
324
+ ### Request Options
325
+
326
+ ```ruby
327
+ {
328
+ body: '{"key": "value"}', # Request body (String or Hash)
329
+ query: { param: 'value' }, # Query parameters (Hash)
330
+ headers: { 'X-Custom': 'value' }, # Additional headers (Hash)
331
+ timeout: 30, # Override request timeout
332
+ open_timeout: 10 # Override connection timeout
333
+ }
334
+ ```
335
+
336
+ ## ❌ Error Handling
337
+
338
+ ### Exception Types
339
+
340
+ | Exception | Reason | Action |
341
+ |-----------|---------|----------|
342
+ | `InsecureConnectionError` | HTTP used in production with `ssl_verify: true` | Use HTTPS |
343
+ | `InvalidCredentialsError` | Missing `base_uri` or `public_key` | Check configuration |
344
+ | `SecurityError` | Key does not match the scheme, or encryption failed | Pass a public key of the same scheme in PEM |
345
+ | `Timeout::Error` | Timeout exceeded | Increase timeout or check service |
346
+ | `SocketError` | Service unavailable | Check base_uri and network |
347
+
348
+ ### Error Handling
349
+
350
+ ```ruby
351
+ begin
352
+ response = RobustClientSocket::Payments.post(
353
+ '/api/v1/charge',
354
+ body: { amount: 1000 }.to_json
355
+ )
356
+
357
+ if response.success?
358
+ # Success
359
+ elsif response.code == 401
360
+ # Authorization problem
361
+ Rails.logger.error("Auth failed: token may be rejected by server")
362
+ elsif response.code == 422
363
+ # Validation error
364
+ errors = response.parsed_response['errors']
365
+ elsif response.code >= 500
366
+ # Server error
367
+ Rails.logger.error("Server error: #{response.code}")
368
+ end
369
+
370
+ rescue RobustClientSocket::HTTP::Client::InsecureConnectionError => e
371
+ Rails.logger.error("Insecure connection: #{e.message}")
372
+ # Use HTTPS in production
373
+
374
+ rescue Timeout::Error => e
375
+ Rails.logger.error("Request timeout: #{e.message}")
376
+ # Retry or timeout handling
377
+
378
+ rescue SocketError => e
379
+ Rails.logger.error("Service unavailable: #{e.message}")
380
+ # Service unavailable
381
+
382
+ rescue SecurityError => e
383
+ Rails.logger.error("Security error: #{e.message}")
384
+ # Problem with keys or encryption
385
+
386
+ rescue StandardError => e
387
+ Rails.logger.error("Unexpected error: #{e.class} - #{e.message}")
388
+ end
389
+ ```
390
+
391
+ ## 🔐 SSL/TLS Settings
392
+
393
+ ### Production Configuration
394
+
395
+ ```ruby
396
+ RobustClientSocket.configure do |c|
397
+ c.client_name = 'core'
398
+
399
+ c.payments = {
400
+ base_uri: 'https://payments.example.com',
401
+ public_key: ENV['PAYMENTS_PUBLIC_KEY'],
402
+
403
+ # Enable SSL validation
404
+ ssl_verify: true,
405
+
406
+ # TLS 1.2+ with secure ciphers
407
+ ciphers: %w[
408
+ ECDHE-ECDSA-AES128-GCM-SHA256
409
+ ECDHE-ECDSA-AES256-GCM-SHA384
410
+ ECDHE-ECDSA-CHACHA20-POLY1305
411
+ ]
412
+ }
413
+ end
414
+ ```
415
+
416
+ ### 2. Synchronization with Server
417
+
418
+ ```ruby
419
+ # Client
420
+ RobustClientSocket.configure do |c|
421
+ c.client_name = 'core' # ← Important: current service name
422
+
423
+ c.payments = {
424
+ base_uri: 'https://payments.example.com',
425
+ public_key: '-----BEGIN PUBLIC KEY-----...' # PAYMENTS service public key
426
+ }
427
+ end
428
+
429
+ # Server (payments)
430
+ RobustServerSocket.configure do |c|
431
+ c.allowed_services = %w[core] # ← Must contain 'core'
432
+ c.private_key = '-----BEGIN PRIVATE KEY-----...' # Private pair to public key above
433
+ end
434
+ ```
435
+
436
+ ## 🤝 Integration with RobustServerSocket
437
+
438
+ ### Full Setup Example
439
+
440
+ **Service A (client):**
441
+ ```ruby
442
+ # config/initializers/robust_client_socket.rb
443
+ RobustClientSocket.configure do |c|
444
+ c.client_name = 'service_a'
445
+
446
+ c.service_b = {
447
+ base_uri: ENV['SERVICE_B_URL'],
448
+ public_key: ENV['SERVICE_B_PUBLIC_KEY'],
449
+ ssl_verify: Rails.env.production?
450
+ }
451
+ end
452
+
453
+ RobustClientSocket.load!
454
+ ```
455
+
456
+ **Service B (server):**
457
+ ```ruby
458
+ # config/initializers/robust_server_socket.rb
459
+ RobustServerSocket.configure do |c|
460
+ c.allowed_services = %w[service_a] # Allow service_a
461
+ c.private_key = ENV['SERVICE_B_PRIVATE_KEY']
462
+ c.token_expiration_time = 3
463
+ c.redis_url = ENV['REDIS_URL']
464
+ c.redis_pass = ENV['REDIS_PASSWORD']
465
+ end
466
+
467
+ RobustServerSocket.load!
468
+ ```
469
+
470
+ **Key Pair Generation:**
471
+ ```bash
472
+ # X25519 private key (for Service B)
473
+ openssl genpkey -algorithm X25519 -out service_b_private.pem
474
+
475
+ # Public key (for Service A)
476
+ openssl pkey -in service_b_private.pem -pubout -out service_b_public.pem
477
+
478
+ # Add to environment variables
479
+ # Service A: SERVICE_B_PUBLIC_KEY=$(cat service_b_public.pem)
480
+ # Service B: SERVICE_B_PRIVATE_KEY=$(cat service_b_private.pem)
481
+ ```
482
+
483
+ ## 📚 Additional Resources
484
+
485
+ - [BENCHMARK_ANALYSIS.md](../BENCHMARK_ANALYSIS.md)
486
+ - [RobustServerSocket documentation](../robust_server_socket/README.ru.md)
487
+ - [HTTParty documentation](https://github.com/jnunemaker/httparty)
488
+ - [OpenSSL Ruby documentation](https://ruby-doc.org/stdlib/libdoc/openssl/rdoc/OpenSSL.html)
489
+
490
+ ## 📝 License
491
+
492
+ See [LICENSE.txt](LICENSE.txt) file
493
+
494
+ ## 🐛 Bugs and Suggestions
495
+
496
+ Report issues to my telegram @cruel_mango or to email tee0zed@gmail.com