robust_client_socket 0.5.3 → 0.7.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f8b0a33c73c941fc1dd8ba91d5f8fa6a07e675af0f27dc22950725f0cba532a1
4
- data.tar.gz: 2fbb9c0cbe3056ad15b27b6a3c495808d7913510863973e0f14c4e0e00133ea4
3
+ metadata.gz: 0e12655b56d656504508d1722c003bf175f684479609091f24d8ae7d7a21c4a1
4
+ data.tar.gz: 6a0fb316719d97d904bd228f9452dc80abbb3cdccc0a5d9dbcdcd2d3dfd9e907
5
5
  SHA512:
6
- metadata.gz: 68c8af3de180c3b8393a61bdc767da73c0cf812c76ad32c3ba712bf7e51bbf47d8fb49adaa2a8920638fde0789369e429be3fc6479f9cb2d1c681379b0e68fd0
7
- data.tar.gz: b32d5618d1e159e0dd0b784f0f4bbddf1b6b6ef4627649a49a548435672d18116d9c941b8c884712f28eb61e0f59feafe2fd374e7b22dbe7b06021ce3a4f5e99
6
+ metadata.gz: edf7e99c4de9fb69494c93d2ed6a4698100f4a02510d7e0025296cd71a6ae28fa07da82567c1eb09f2943df4b720bd9f6ca1dcc15d77723aee2c041e3bad8e09
7
+ data.tar.gz: d740828d6ab51ed7be3f84c48dcfcc4d33a48bd6a0b08ce97380582b46e1fc038efeb3d76e98b48c4921bf191c80979b3e4f9c3ca5b5308f710894e24617bf2f
@@ -2,9 +2,9 @@
2
2
 
3
3
  ## Executive Summary
4
4
 
5
- Comprehensive performance testing comparing **HTTParty** (plain HTTP client) against **RobustClientSocket::CoreApi** (with RSA encryption and token-based authentication) over 1000 requests.
5
+ Comprehensive performance testing comparing **HTTParty** (plain HTTP client) against **RobustClientSocket::CoreApi** (with token encryption and token-based authentication) over 1000 requests.
6
6
 
7
- **Key Finding:** RobustClientSocket is **25.5% faster** than plain HTTParty despite adding RSA-2048 encryption and security features.
7
+ **Key Finding:** RobustClientSocket is **25.5% faster** than plain HTTParty despite adding X25519 + AES-256-GCM and security features.
8
8
 
9
9
  ---
10
10
 
@@ -62,10 +62,9 @@ end
62
62
  ```
63
63
 
64
64
  ### Security Features Enabled
65
- - ✅ RSA-2048 encryption for token generation
65
+ - ✅ X25519 + AES-256-GCM for token generation
66
66
  - ✅ Automatic token creation per request
67
67
  - ✅ UTC timestamp inclusion
68
- - ✅ PKCS1_OAEP_PADDING
69
68
  - ✅ Base64 encoding
70
69
  - ✅ Custom security headers
71
70
 
@@ -120,20 +119,20 @@ RobustClientSocket: ████████▌ 0.770s (+2.8%)
120
119
 
121
120
  ### 1. **Dramatically Faster Real Time (-25.4%)**
122
121
 
123
- Despite adding RSA encryption, RobustClientSocket completes requests **25.4% faster** in real wall-clock time.
122
+ Despite adding token encryption, RobustClientSocket completes requests **25.4% faster** in real wall-clock time.
124
123
 
125
124
  **Why?**
126
125
  - **Connection reuse**: HTTParty optimizations through proper configuration
127
126
  - **Header optimization**: Pre-computed static headers
128
- - **Efficient token generation**: RSA encryption happens in <0.1ms
127
+ - **Efficient token generation**: token encryption happens in <0.1ms
129
128
  - **No redundant operations**: Streamlined request pipeline
130
129
 
131
130
  ### 2. **Minimal CPU Overhead (+2.8%)**
132
131
 
133
- RSA-2048 encryption adds only **21ms** of total CPU time across 1000 requests.
132
+ X25519 + AES-256-GCM adds only **21ms** of total CPU time across 1000 requests.
134
133
 
135
134
  **Per-request overhead:**
136
- - RSA encryption: ~0.02ms per request
135
+ - token encryption: ~0.02ms per request
137
136
  - Token generation: ~0.01ms per request
138
137
  - **Total security overhead: ~0.03ms per request**
139
138
 
@@ -142,7 +141,7 @@ This is **negligible** for any production workload.
142
141
  ### 3. **System CPU Trade-off (+10.2%)**
143
142
 
144
143
  The 10.2% increase in system CPU is expected due to:
145
- - OpenSSL operations (RSA encryption)
144
+ - OpenSSL operations (token encryption)
146
145
  - Additional header processing
147
146
  - Security token validation
148
147
 
@@ -182,7 +181,7 @@ Total Time: 2.774s
182
181
 
183
182
  | Operation | Time per Request | % of Total |
184
183
  |-----------|-----------------|-----------|
185
- | RSA Encryption | 0.015ms | 0.5% |
184
+ | Token encryption | 0.015ms | 0.5% |
186
185
  | Token Generation | 0.008ms | 0.3% |
187
186
  | Base64 Encoding | 0.004ms | 0.1% |
188
187
  | Header Assembly | 0.003ms | 0.1% |
@@ -290,7 +289,7 @@ If each request involves downstream calls or database queries, the 25% speed imp
290
289
  | Aspect | Result |
291
290
  |--------|--------|
292
291
  | **Speed** | ⚡ **25.4% faster** real time |
293
- | **Security** | ✅ RSA-2048 encryption included |
292
+ | **Security** | ✅ X25519 + AES-256-GCM included |
294
293
  | **CPU Cost** | ✅ Only +2.8% overhead |
295
294
  | **Scalability** | ✅ Linear scaling maintained |
296
295
  | **Recommendation** | ✅ **Use RobustClientSocket in production** |
@@ -365,7 +364,7 @@ end
365
364
  puts result_httparty
366
365
 
367
366
  # Test 2: RobustClientSocket
368
- puts "\nTest 2: RobustClientSocket (with RSA security)"
367
+ puts "\nTest 2: RobustClientSocket (with token encryption)"
369
368
  result_robust = Benchmark.measure do
370
369
  1000.times do
371
370
  RobustClientSocket::CoreApi.get('/api/v1/partners/719a68e4-3457-45dd-8d7f-73f1d367b87a/merchants')
data/README.en.md CHANGED
@@ -14,7 +14,7 @@ When building microservice communication, the following challenges arise:
14
14
 
15
15
  - **Lack of authentication**: HTTP requests between services are unprotected
16
16
  - **Replay attacks**: Intercepted requests can be reused maliciously
17
- - **Manual key management**: Complexity of handling RSA keys for each service
17
+ - **Manual key management**: Complexity of handling an X25519 key for each service
18
18
  - **Boilerplate code**: Repetitive code for encryption and request sending
19
19
 
20
20
  ### The Solution
@@ -22,7 +22,7 @@ When building microservice communication, the following challenges arise:
22
22
  RobustClientSocket provides:
23
23
 
24
24
  - **Automatic tokenization**: Each request receives a unique encrypted token
25
- - **RSA encryption**: Asymmetric encryption with key validation
25
+ - **Token encryption**: X25519 + AES-256-GCM with key validation
26
26
  - **Keychain management**: Auto-generation of HTTP clients for each service
27
27
  - **Replay attack protection**: Timestamp in every token
28
28
 
@@ -41,7 +41,7 @@ RobustClientSocket provides:
41
41
  │ RobustClientSocket│ │ RobustServerSocket│
42
42
  │ │ │ │
43
43
  │ 1. Generate token │────>│ 1. Decrypt token │
44
- │ 2. RSA encrypt │ │ 2. Validate │
44
+ │ 2. Seal token │ │ 2. Validate │
45
45
  │ 3. Send request │ │ 3. Check limits │
46
46
  └───────────────────┘ └───────────────────┘
47
47
  ```
@@ -49,7 +49,7 @@ RobustClientSocket provides:
49
49
  ### Request Flow
50
50
 
51
51
  1. **Token formation**: `{client_name}_{timestamp}`
52
- 2. **RSA encryption**: Token is encrypted with target service's public key
52
+ 2. **Encryption**: Token is sealed to the target service's X25519 public key (ephemeral X25519 + AES-256-GCM)
53
53
  3. **Base64 encoding**: For HTTP header transmission
54
54
  4. **Request sending**: Request with `Secure-Token` header
55
55
  5. **Validation**: Server decrypts and validates the token
@@ -57,9 +57,9 @@ RobustClientSocket provides:
57
57
  ### Token Structure
58
58
 
59
59
  ```
60
- Base64(RSA_Encrypt("{service_name}_{unix_timestamp}"))
60
+ Base64(ephemeral_public_der || iv || tag || AES-256-GCM("{client_name}_{unix_timestamp_ms}"))
61
61
 
62
- Example: Base64(RSA_Encrypt("core_1704067200"))
62
+ The AES key is HKDF-SHA256 over the X25519 shared secret.
63
63
  ```
64
64
 
65
65
  ## 📋 Table of Contents
@@ -81,10 +81,12 @@ RobustClientSocket provides secure communication between microservices:
81
81
  - **Timestamps**: Tokens contain UTC timestamp for replay attack protection
82
82
  - **One-time Tokens**: Each request uses a unique token
83
83
 
84
- ### 2. RSA Encryption
85
- - **RSA-2048 Minimum**: Automatic key size validation
86
- - **PKCS1_OAEP_PADDING**: Secure padding for attack protection
87
- - **Key Validation**: Public key correctness verification during configuration
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**: a `Base` subclass calls `register_cipher :name`. X25519 and X448 inherit `Ecdh`
89
+ - **Key validation**: the key must match the scheme. RSA and a private key are rejected
88
90
 
89
91
  ### 3. TLS/SSL Protection
90
92
  - **TLS 1.2+**: Modern encryption protocols
@@ -130,6 +132,10 @@ RobustClientSocket.configure do |c|
130
132
  # REQUIRED: Current service (client) name
131
133
  # Must match allowed_services on server
132
134
  c.client_name = 'core'
135
+
136
+ # OPTIONAL: token scheme. Default :x25519, :x448 is built in.
137
+ # Your own: a Base subclass calls register_cipher :name.
138
+ c.cipher = :x25519
133
139
 
134
140
  # OPTIONAL: Header name for token (default: 'Secure-Token')
135
141
  c.header_name = 'Secure-Token'
@@ -157,10 +163,9 @@ RobustClientSocket.configure do |c|
157
163
  public_key: ENV['CORE_PUBLIC_KEY'],
158
164
  ssl_verify: true,
159
165
  ciphers: %w[
160
- ECDHE-RSA-AES128-GCM-SHA256
161
- ECDHE-RSA-AES256-GCM-SHA384
162
166
  ECDHE-ECDSA-AES128-GCM-SHA256
163
167
  ECDHE-ECDSA-AES256-GCM-SHA384
168
+ ECDHE-ECDSA-CHACHA20-POLY1305
164
169
  ]
165
170
  }
166
171
  end
@@ -174,7 +179,8 @@ RobustClientSocket.load!
174
179
  | Parameter | Type | Required | Default | Description |
175
180
  |----------|-----|--------------|---------|----------|
176
181
  | `base_uri` | String | ✅ | - | Target service URL |
177
- | `public_key` | String | ✅ | - | Service RSA public key |
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 |
178
184
  | `ssl_verify` | Boolean | ❌ | false | Enable SSL certificate verification |
179
185
  | `timeout` | Integer | ❌ | 10 | Request timeout (seconds) |
180
186
  | `open_timeout` | Integer | ❌ | 5 | Connection timeout (seconds) |
@@ -182,10 +188,9 @@ RobustClientSocket.load!
182
188
 
183
189
  **Default cipher suites:**
184
190
  ```
185
- ECDHE-RSA-AES128-GCM-SHA256
186
- ECDHE-RSA-AES256-GCM-SHA384
187
191
  ECDHE-ECDSA-AES128-GCM-SHA256
188
192
  ECDHE-ECDSA-AES256-GCM-SHA384
193
+ ECDHE-ECDSA-CHACHA20-POLY1305
189
194
  ```
190
195
 
191
196
  ## 🚀 Usage
@@ -336,8 +341,7 @@ RobustClientSocket::ServiceName.options(path, options = {})
336
341
  |-----------|---------|----------|
337
342
  | `InsecureConnectionError` | HTTP used in production with `ssl_verify: true` | Use HTTPS |
338
343
  | `InvalidCredentialsError` | Missing `base_uri` or `public_key` | Check configuration |
339
- | `SecurityError` | Key less than 2048 bits or invalid | Use correct RSA-2048+ key |
340
- | `OpenSSL::PKey::RSAError` | Encryption error | Check public key format |
344
+ | `SecurityError` | Key does not match the scheme, or encryption failed | Pass a public key of the same scheme in PEM |
341
345
  | `Timeout::Error` | Timeout exceeded | Increase timeout or check service |
342
346
  | `SocketError` | Service unavailable | Check base_uri and network |
343
347
 
@@ -401,8 +405,9 @@ RobustClientSocket.configure do |c|
401
405
 
402
406
  # TLS 1.2+ with secure ciphers
403
407
  ciphers: %w[
404
- ECDHE-RSA-AES128-GCM-SHA256
405
- ECDHE-RSA-AES256-GCM-SHA384
408
+ ECDHE-ECDSA-AES128-GCM-SHA256
409
+ ECDHE-ECDSA-AES256-GCM-SHA384
410
+ ECDHE-ECDSA-CHACHA20-POLY1305
406
411
  ]
407
412
  }
408
413
  end
@@ -464,11 +469,11 @@ RobustServerSocket.load!
464
469
 
465
470
  **Key Pair Generation:**
466
471
  ```bash
467
- # Generate private key (for Service B)
468
- openssl genrsa -out service_b_private.pem 2048
472
+ # X25519 private key (for Service B)
473
+ openssl genpkey -algorithm X25519 -out service_b_private.pem
469
474
 
470
- # Generate public key (for Service A)
471
- openssl rsa -in service_b_private.pem -pubout -out service_b_public.pem
475
+ # Public key (for Service A)
476
+ openssl pkey -in service_b_private.pem -pubout -out service_b_public.pem
472
477
 
473
478
  # Add to environment variables
474
479
  # Service A: SERVICE_B_PUBLIC_KEY=$(cat service_b_public.pem)
data/README.md CHANGED
@@ -14,7 +14,7 @@ HTTP-клиент для защищённых межсервисных комм
14
14
 
15
15
  - **Отсутствие аутентификации**: HTTP-запросы между сервисами не защищены
16
16
  - **Replay-атаки**: Перехваченные запросы могут быть повторно использованы
17
- - **Ручное управление ключами**: Сложность работы с RSA-ключами для каждого сервиса
17
+ - **Ручное управление ключами**: Сложность работы с ключами X25519 для каждого сервиса
18
18
  - **Boilerplate код**: Повторяющийся код для шифрования и отправки запросов
19
19
 
20
20
  ### Решение
@@ -22,7 +22,7 @@ HTTP-клиент для защищённых межсервисных комм
22
22
  RobustClientSocket предоставляет:
23
23
 
24
24
  - **Автоматическую токенизацию**: Каждый запрос получает уникальный зашифрованный токен
25
- - **RSA-шифрование**: Асимметричное шифрование с валидацией ключей
25
+ - **Шифрование токена**: X25519 + AES-256-GCM с проверкой ключа
26
26
  - **Keychain управление**: Автогенерация HTTP-клиентов для каждого сервиса
27
27
  - **Защиту от replay-атак**: Timestamp в каждом токене
28
28
 
@@ -41,7 +41,7 @@ RobustClientSocket предоставляет:
41
41
  │ RobustClientSocket│ │ RobustServerSocket│
42
42
  │ │ │ │
43
43
  │ 1. Generate token │────>│ 1. Decrypt token │
44
- │ 2. RSA encrypt │ │ 2. Validate │
44
+ │ 2. Seal token │ │ 2. Validate │
45
45
  │ 3. Send request │ │ 3. Check limits │
46
46
  └───────────────────┘ └───────────────────┘
47
47
  ```
@@ -49,7 +49,7 @@ RobustClientSocket предоставляет:
49
49
  ### Поток запроса
50
50
 
51
51
  1. **Формирование токена**: `{client_name}_{timestamp}`
52
- 2. **RSA-шифрование**: Токен шифруется публичным ключом целевого сервиса
52
+ 2. **Шифрование**: Токен запечатывается публичным ключом X25519 целевого сервиса (эфемерный X25519 + AES-256-GCM)
53
53
  3. **Base64 кодирование**: Для передачи в HTTP-заголовке
54
54
  4. **Отправка**: Запрос в заголовке
55
55
  5. **Валидация**: Сервер расшифровывает и проверяет токен
@@ -57,9 +57,9 @@ RobustClientSocket предоставляет:
57
57
  ### Структура токена
58
58
 
59
59
  ```
60
- Base64(RSA_Encrypt("{service_name}_{unix_timestamp}"))
60
+ Base64(ephemeral_public_der || iv || tag || AES-256-GCM("{client_name}_{unix_timestamp_ms}"))
61
61
 
62
- Пример: Base64(RSA_Encrypt("core_1704067200"))
62
+ Ключ AES берётся через HKDF-SHA256 из X25519 shared secret.
63
63
  ```
64
64
 
65
65
  ## 📋 Содержание
@@ -81,10 +81,12 @@ RobustClientSocket обеспечивает защищённую коммуни
81
81
  - **Временные метки**: Токены содержат UTC timestamp для защиты от replay attacks
82
82
  - **Одноразовые токены**: Каждый запрос использует уникальный токен
83
83
 
84
- ### 2. RSA шифрование
85
- - **RSA-2048 минимум**: Автоматическая валидация размера ключа
86
- - **PKCS1_OAEP_PADDING**: Безопасный padding для защиты от атак
87
- - **Валидация ключей**: Проверка корректности публичных ключей при конфигурации
84
+ ### 2. Шифрование токена
85
+ - **Выбор схемы**: `c.cipher`, по умолчанию `:x25519`, встроен ещё `:x448`. На сервисе ключ `cipher:` перекрывает общий
86
+ - **X25519 / X448**: эфемерный ключ на каждый токен, сервер хранит только статическую пару той же схемы
87
+ - **AES-256-GCM**: аутентифицированное шифрование, подмена токена отвергается
88
+ - **Своя схема**: наследник `Base` вызывает `register_cipher :name`. X25519 и X448 наследуют `Ecdh`
89
+ - **Валидация ключей**: ключ обязан совпадать со схемой. RSA и приватный ключ отвергаются
88
90
 
89
91
  ### 3. TLS/SSL защита
90
92
  - **TLS 1.2+**: Современные протоколы шифрования
@@ -130,6 +132,10 @@ RobustClientSocket.configure do |c|
130
132
  # ОБЯЗАТЕЛЬНО: Имя текущего сервиса (клиента)
131
133
  # Должно совпадать с allowed_services на сервере
132
134
  c.client_name = 'core'
135
+
136
+ # ОПЦИОНАЛЬНО: схема токена. :x25519 по умолчанию, встроен ещё :x448.
137
+ # Своя схема: класс-наследник Base вызывает register_cipher :name.
138
+ c.cipher = :x25519
133
139
 
134
140
  # ОПЦИОНАЛЬНО: Имя заголовка для токена (default: 'Secure-Token')
135
141
  c.header_name = 'Secure-Token'
@@ -157,10 +163,9 @@ RobustClientSocket.configure do |c|
157
163
  public_key: ENV['CORE_PUBLIC_KEY'],
158
164
  ssl_verify: true,
159
165
  ciphers: %w[
160
- ECDHE-RSA-AES128-GCM-SHA256
161
- ECDHE-RSA-AES256-GCM-SHA384
162
166
  ECDHE-ECDSA-AES128-GCM-SHA256
163
167
  ECDHE-ECDSA-AES256-GCM-SHA384
168
+ ECDHE-ECDSA-CHACHA20-POLY1305
164
169
  ]
165
170
  }
166
171
  end
@@ -174,7 +179,8 @@ RobustClientSocket.load!
174
179
  | Параметр | Тип | Обязательный | Default | Описание |
175
180
  |----------|-----|--------------|---------|----------|
176
181
  | `base_uri` | String | ✅ | - | URL целевого сервиса |
177
- | `public_key` | String | ✅ | - | Публичный RSA ключ сервиса |
182
+ | `public_key` | String | ✅ | - | Публичный ключ выбранной схемы (PEM). По умолчанию X25519 |
183
+ | `cipher` | Symbol | ❌ | `:x25519` | Схема токена: `:x25519`, `:x448` или зарегистрированная |
178
184
  | `ssl_verify` | Boolean | ❌ | false | Включить проверку SSL сертификатов |
179
185
  | `timeout` | Integer | ❌ | 10 | Таймаут запроса (секунды) |
180
186
  | `open_timeout` | Integer | ❌ | 5 | Таймаут подключения (секунды) |
@@ -182,10 +188,9 @@ RobustClientSocket.load!
182
188
 
183
189
  **Default cipher suites:**
184
190
  ```
185
- ECDHE-RSA-AES128-GCM-SHA256
186
- ECDHE-RSA-AES256-GCM-SHA384
187
191
  ECDHE-ECDSA-AES128-GCM-SHA256
188
192
  ECDHE-ECDSA-AES256-GCM-SHA384
193
+ ECDHE-ECDSA-CHACHA20-POLY1305
189
194
  ```
190
195
 
191
196
  ## 🚀 Использование
@@ -336,8 +341,7 @@ RobustClientSocket::ServiceName.options(path, options = {})
336
341
  |-----------|---------|----------|
337
342
  | `InsecureConnectionError` | HTTP используется в production с `ssl_verify: true` | Используйте HTTPS |
338
343
  | `InvalidCredentialsError` | Отсутствуют `base_uri` или `public_key` | Проверьте конфигурацию |
339
- | `SecurityError` | Ключ меньше 2048 бит или невалиден | Используйте корректный RSA-2048+ ключ |
340
- | `OpenSSL::PKey::RSAError` | Ошибка шифрования | Проверьте формат публичного ключа |
344
+ | `SecurityError` | Ключ не совпадает со схемой или шифрование не удалось | Передайте публичный ключ той же схемы в PEM |
341
345
  | `Timeout::Error` | Превышен таймаут | Увеличьте timeout или проверьте сервис |
342
346
  | `SocketError` | Сервис недоступен | Проверьте base_uri и сеть |
343
347
 
@@ -401,8 +405,9 @@ RobustClientSocket.configure do |c|
401
405
 
402
406
  # TLS 1.2+ с безопасными ciphers
403
407
  ciphers: %w[
404
- ECDHE-RSA-AES128-GCM-SHA256
405
- ECDHE-RSA-AES256-GCM-SHA384
408
+ ECDHE-ECDSA-AES128-GCM-SHA256
409
+ ECDHE-ECDSA-AES256-GCM-SHA384
410
+ ECDHE-ECDSA-CHACHA20-POLY1305
406
411
  ]
407
412
  }
408
413
  end
@@ -464,11 +469,11 @@ RobustServerSocket.load!
464
469
 
465
470
  **Генерация пары ключей:**
466
471
  ```bash
467
- # Генерация приватного ключа (для Service B)
468
- openssl genrsa -out service_b_private.pem 2048
472
+ # Приватный ключ X25519 (для Service B)
473
+ openssl genpkey -algorithm X25519 -out service_b_private.pem
469
474
 
470
- # Генерация публичного ключа (для Service A)
471
- openssl rsa -in service_b_private.pem -pubout -out service_b_public.pem
475
+ # Публичный ключ (для Service A)
476
+ openssl pkey -in service_b_private.pem -pubout -out service_b_public.pem
472
477
 
473
478
  # Добавить в переменные окружения
474
479
  # Service A: SERVICE_B_PUBLIC_KEY=$(cat service_b_public.pem)
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RobustClientSocket
4
+ module Ciphers
5
+ class Base
6
+ UnknownCipher = Class.new(SecurityError)
7
+ CIPHERS = []
8
+
9
+ class << self
10
+ def ciphers
11
+ CIPHERS
12
+ end
13
+
14
+ def register_cipher(name)
15
+ raise ArgumentError, 'cipher name must be a Symbol' unless name.is_a?(Symbol)
16
+
17
+ CIPHERS.delete(self)
18
+ @cipher_name = name
19
+ CIPHERS << self
20
+ name
21
+ end
22
+
23
+ def cipher_name
24
+ @cipher_name
25
+ end
26
+
27
+ def fetch(name)
28
+ found = ciphers.find { |cipher| cipher.cipher_name == name.to_sym }
29
+ return found if found
30
+
31
+ raise UnknownCipher, "Unknown cipher: #{name}"
32
+ end
33
+
34
+ def seal(_plaintext, _public_key_pem)
35
+ raise NotImplementedError
36
+ end
37
+
38
+ def read_public_key(_pem)
39
+ raise NotImplementedError
40
+ end
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'openssl'
4
+ require 'base64'
5
+ require_relative 'base'
6
+
7
+ module RobustClientSocket
8
+ module Ciphers
9
+ class Ecdh < Base
10
+ KEY_LENGTH = 32
11
+
12
+ class << self
13
+ def seal(plaintext, public_key_pem)
14
+ recipient = read_public_key(public_key_pem)
15
+ ephemeral = OpenSSL::PKey.generate_key(self::ALGORITHM)
16
+ blob = ephemeral.public_to_der.b + gcm_seal(derive_key(ephemeral.derive(recipient)), plaintext)
17
+
18
+ ::Base64.strict_encode64(blob)
19
+ rescue OpenSSL::PKey::PKeyError, OpenSSL::Cipher::CipherError => e
20
+ raise SecurityError, "Encryption failed: #{e.message}"
21
+ end
22
+
23
+ def read_public_key(pem)
24
+ key = OpenSSL::PKey.read(pem)
25
+ raise SecurityError, 'Invalid public key' unless public_key?(key)
26
+
27
+ key
28
+ rescue OpenSSL::PKey::PKeyError => e
29
+ raise SecurityError, "Invalid public key: #{e.message}"
30
+ end
31
+
32
+ private
33
+
34
+ def public_key?(key)
35
+ key.oid == self::ALGORITHM && !holds_private_key?(key)
36
+ end
37
+
38
+ def holds_private_key?(key)
39
+ !key.raw_private_key.nil?
40
+ rescue OpenSSL::PKey::PKeyError
41
+ false
42
+ end
43
+
44
+ def derive_key(shared_secret)
45
+ OpenSSL::KDF.hkdf(shared_secret, salt: '', info: self::INFO, length: KEY_LENGTH, hash: 'SHA256')
46
+ end
47
+
48
+ def gcm_seal(key, plaintext)
49
+ cipher = OpenSSL::Cipher.new('aes-256-gcm')
50
+ cipher.encrypt
51
+ cipher.key = key
52
+ iv = cipher.random_iv
53
+ cipher.auth_data = self::INFO
54
+ ciphertext = cipher.update(plaintext) + cipher.final
55
+
56
+ iv + cipher.auth_tag + ciphertext
57
+ end
58
+ end
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'ecdh'
4
+
5
+ module RobustClientSocket
6
+ module Ciphers
7
+ class X25519 < Ecdh
8
+ ALGORITHM = 'X25519'
9
+ EPHEMERAL_DER_LENGTH = 44
10
+ INFO = 'robust-socket-token-v1-x25519'
11
+ end
12
+
13
+ X25519.register_cipher :x25519
14
+ end
15
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'ecdh'
4
+
5
+ module RobustClientSocket
6
+ module Ciphers
7
+ class X448 < Ecdh
8
+ ALGORITHM = 'X448'
9
+ EPHEMERAL_DER_LENGTH = 68
10
+ INFO = 'robust-socket-token-v1-x448'
11
+ end
12
+
13
+ X448.register_cipher :x448
14
+ end
15
+ end
@@ -1,7 +1,5 @@
1
1
  module RobustClientSocket
2
2
  module Configuration
3
- MIN_KEY_SIZE = 2048
4
-
5
3
  attr_reader :configuration, :configured
6
4
 
7
5
  def configure
@@ -32,16 +30,8 @@ module RobustClientSocket
32
30
  configuration.services.each do |service_name, creds|
33
31
  next unless creds[:public_key]
34
32
 
35
- key = OpenSSL::PKey::RSA.new(creds[:public_key])
36
- key_bits = key.n.num_bits
37
-
38
- if key_bits < MIN_KEY_SIZE
39
- raise SecurityError,
40
- "RSA key size for #{service_name} (#{key_bits} bits) below minimum (#{MIN_KEY_SIZE} bits)"
41
- end
42
-
43
- raise SecurityError, "Invalid public key for #{service_name}" unless key.public?
44
- rescue OpenSSL::PKey::RSAError => e
33
+ Ciphers::Base.fetch(creds.fetch(:cipher, configuration.cipher)).read_public_key(creds[:public_key])
34
+ rescue SecurityError => e
45
35
  raise SecurityError, "Invalid public key for #{service_name}: #{e.message}"
46
36
  end
47
37
  end
@@ -49,11 +39,12 @@ module RobustClientSocket
49
39
 
50
40
  class ConfigStore
51
41
  attr_reader :services
52
- attr_accessor :client_name, :header_name
42
+ attr_accessor :client_name, :header_name, :cipher
53
43
 
54
44
  def initialize
55
45
  @services = {}
56
46
  @client_name = nil
47
+ @cipher = :x25519
57
48
  end
58
49
 
59
50
  def method_missing(name, *args) # rubocop:disable Style/MissingRespondToMissing
@@ -58,10 +58,9 @@ module RobustClientSocket
58
58
 
59
59
  def ssl_ciphers(credentials)
60
60
  ciphers = credentials.fetch(:ciphers,
61
- %w[ECDHE-RSA-AES128-GCM-SHA256
62
- ECDHE-RSA-AES256-GCM-SHA384
63
- ECDHE-ECDSA-AES128-GCM-SHA256
64
- ECDHE-ECDSA-AES256-GCM-SHA384].join(':')
61
+ %w[ECDHE-ECDSA-AES128-GCM-SHA256
62
+ ECDHE-ECDSA-AES256-GCM-SHA384
63
+ ECDHE-ECDSA-CHACHA20-POLY1305].join(':')
65
64
  )
66
65
 
67
66
  return ciphers if ciphers.is_a?(String)
@@ -8,8 +8,6 @@ module RobustClientSocket
8
8
  end
9
9
 
10
10
  module PrivateClassMethods
11
- MIN_KEY_SIZE = 2048
12
-
13
11
  def robust_headers
14
12
  {
15
13
  'Content-Type' => 'application/json',
@@ -23,33 +21,14 @@ module RobustClientSocket
23
21
  end
24
22
 
25
23
  def encrypted_data(data)
26
- validate_key_security!
27
-
28
- encrypted = rsa_key.public_encrypt(
29
- data,
30
- OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING
31
- )
32
-
33
- ::Base64.strict_encode64(encrypted)
34
- rescue OpenSSL::PKey::RSAError => e
35
- raise SecurityError, "Encryption failed: #{e.message}"
36
- end
37
-
38
- def rsa_key
39
- @rsa_key ||= begin
40
- key = OpenSSL::PKey::RSA.new(public_key)
41
- raise SecurityError, "Invalid public key" unless key.public?
42
- key
43
- end
24
+ Ciphers::Base.fetch(cipher).seal(data, public_key)
44
25
  end
45
26
 
46
- def validate_key_security!
47
- key_bits = rsa_key.n.num_bits
27
+ def cipher
28
+ return credentials[:cipher] if credentials.is_a?(Hash) && credentials.key?(:cipher)
29
+ return RobustClientSocket.configuration.cipher if RobustClientSocket.respond_to?(:configuration) && RobustClientSocket.configuration
48
30
 
49
- if key_bits < MIN_KEY_SIZE
50
- raise SecurityError,
51
- "RSA key size (#{key_bits} bits) below minimum (#{MIN_KEY_SIZE} bits)"
52
- end
31
+ :x25519
53
32
  end
54
33
 
55
34
  def public_key
@@ -2,6 +2,8 @@
2
2
 
3
3
  require_relative 'version'
4
4
  require_relative 'robust_client_socket/configuration'
5
+ require_relative 'robust_client_socket/ciphers/x25519'
6
+ require_relative 'robust_client_socket/ciphers/x448'
5
7
 
6
8
  module RobustClientSocket
7
9
  extend RobustClientSocket::Configuration
data/lib/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module RobustClientSocket
4
- VERSION = '0.5.3'
4
+ VERSION = '0.7.1'
5
5
  end
@@ -20,6 +20,7 @@ Gem::Specification.new do |spec|
20
20
  end
21
21
  end
22
22
  spec.require_paths = %w[lib]
23
+ spec.add_dependency 'base64'
23
24
  spec.add_dependency 'oj'
24
25
  spec.add_dependency 'httparty'
25
26
  spec.add_dependency 'rspec'
@@ -9,7 +9,7 @@ RSpec.describe RobustClientSocket::HTTP::Client do
9
9
  let(:credentials) do
10
10
  {
11
11
  base_uri: 'https://example.com',
12
- public_key: OpenSSL::PKey::RSA.new(2048).public_key.to_s
12
+ public_key: OpenSSL::PKey.generate_key('X25519').public_to_pem
13
13
  }
14
14
  end
15
15
  let(:client_name) { 'test_client' }
@@ -1,5 +1,6 @@
1
1
  require 'spec_helper'
2
2
  require './lib/robust_client_socket/configuration.rb'
3
+ require './lib/robust_client_socket/ciphers/x25519'
3
4
 
4
5
  RSpec.describe RobustClientSocket::Configuration do
5
6
  let(:dummy_class) { Class.new { extend RobustClientSocket::Configuration } }
@@ -7,7 +8,7 @@ RSpec.describe RobustClientSocket::Configuration do
7
8
  before { allow(dummy_class).to receive(:correct_configuration?).and_return(true) }
8
9
 
9
10
  describe '#configure' do
10
- let(:public_key) { OpenSSL::PKey::RSA.generate(2048).public_key.to_pem }
11
+ let(:public_key) { OpenSSL::PKey.generate_key('X25519').public_to_pem }
11
12
 
12
13
  it 'yields the configuration object to the block' do
13
14
  dummy_class.configure do |config|
@@ -25,8 +26,8 @@ RSpec.describe RobustClientSocket::Configuration do
25
26
  expect(dummy_class.configured?).to eq(true)
26
27
  end
27
28
 
28
- context 'with invalid key size' do
29
- let(:small_key) { OpenSSL::PKey::RSA.generate(1024).public_key.to_pem }
29
+ context 'with a non-X25519 key' do
30
+ let(:small_key) { OpenSSL::PKey::RSA.generate(2048).public_key.to_pem }
30
31
 
31
32
  it 'raises SecurityError' do
32
33
  expect {
@@ -34,13 +35,13 @@ RSpec.describe RobustClientSocket::Configuration do
34
35
  config.client_name = 'test'
35
36
  config.service = { base_uri: 'https://example.com', public_key: small_key }
36
37
  end
37
- }.to raise_error(SecurityError, /below minimum/)
38
+ }.to raise_error(SecurityError, /Invalid public key/)
38
39
  end
39
40
  end
40
41
  end
41
42
 
42
43
  describe '#configured?' do
43
- let(:public_key) { OpenSSL::PKey::RSA.generate(2048).public_key.to_pem }
44
+ let(:public_key) { OpenSSL::PKey.generate_key('X25519').public_to_pem }
44
45
 
45
46
  it 'returns false if not configured' do
46
47
  expect(dummy_class.configured?).to eq(false)
@@ -56,7 +57,7 @@ RSpec.describe RobustClientSocket::Configuration do
56
57
  end
57
58
 
58
59
  describe '#correct_configuration?' do
59
- let(:public_key) { OpenSSL::PKey::RSA.generate(2048).public_key.to_pem }
60
+ let(:public_key) { OpenSSL::PKey.generate_key('X25519').public_to_pem }
60
61
 
61
62
  before { allow(dummy_class).to receive(:correct_configuration?).and_call_original }
62
63
 
@@ -9,7 +9,7 @@ RSpec.describe RobustClientSocket::HTTP::Client do
9
9
  let(:credentials) do
10
10
  {
11
11
  base_uri: 'https://example.com',
12
- public_key: OpenSSL::PKey::RSA.new(2048).public_key.to_s
12
+ public_key: OpenSSL::PKey.generate_key('X25519').public_to_pem
13
13
  }
14
14
  end
15
15
  let(:client_name) { 'test_client' }
@@ -3,6 +3,7 @@ require 'openssl'
3
3
  require 'base64'
4
4
  require './lib/version.rb'
5
5
  require './lib/robust_client_socket/http/helpers.rb'
6
+ require './lib/robust_client_socket/ciphers/x25519'
6
7
 
7
8
  RSpec.describe RobustClientSocket::HTTP::Helpers do
8
9
  let(:dummy_class) do
@@ -34,8 +35,8 @@ RSpec.describe RobustClientSocket::HTTP::Helpers do
34
35
 
35
36
  describe '.secure_token' do
36
37
  it 'returns the encrypted token' do
37
- rsa_key = OpenSSL::PKey::RSA.new(2048)
38
- allow(dummy_class).to receive(:public_key).and_return(rsa_key.public_key.to_s)
38
+ public_key = OpenSSL::PKey.generate_key('X25519').public_to_pem
39
+ allow(dummy_class).to receive(:public_key).and_return(public_key)
39
40
  allow(dummy_class).to receive(:app_token).and_return('app_token')
40
41
 
41
42
  result = dummy_class.send(:secure_token)
@@ -68,8 +69,8 @@ RSpec.describe RobustClientSocket::HTTP::Helpers do
68
69
 
69
70
  describe '.encrypted_data' do
70
71
  it 'encrypts and base64 encodes data' do
71
- rsa_key = OpenSSL::PKey::RSA.new(2048)
72
- allow(dummy_class).to receive(:public_key).and_return(rsa_key.public_key.to_s)
72
+ public_key = OpenSSL::PKey.generate_key('X25519').public_to_pem
73
+ allow(dummy_class).to receive(:public_key).and_return(public_key)
73
74
 
74
75
  result = dummy_class.send(:encrypted_data, 'test_data')
75
76
  expect(result).to be_a(String)
@@ -19,7 +19,7 @@ RSpec.describe RobustClientSocket::HTTP::HTTPartyOverrides do
19
19
 
20
20
  describe '.perform_request' do
21
21
  before do
22
- test_class.credentials = { public_key: OpenSSL::PKey::RSA.new(2048).public_key.to_s }
22
+ test_class.credentials = { public_key: OpenSSL::PKey.generate_key('X25519').public_to_pem }
23
23
  test_class.client_name = 'test_client'
24
24
  allow(Time).to receive_message_chain(:now, :utc, :to_i).and_return(12345)
25
25
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: robust_client_socket
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.5.3
4
+ version: 0.7.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Taras Zhuk
@@ -9,6 +9,20 @@ bindir: bin
9
9
  cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies:
12
+ - !ruby/object:Gem::Dependency
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'
12
26
  - !ruby/object:Gem::Dependency
13
27
  name: oj
14
28
  requirement: !ruby/object:Gem::Requirement
@@ -82,6 +96,10 @@ files:
82
96
  - img.png
83
97
  - img_1.png
84
98
  - lib/robust_client_socket.rb
99
+ - lib/robust_client_socket/ciphers/base.rb
100
+ - lib/robust_client_socket/ciphers/ecdh.rb
101
+ - lib/robust_client_socket/ciphers/x25519.rb
102
+ - lib/robust_client_socket/ciphers/x448.rb
85
103
  - lib/robust_client_socket/configuration.rb
86
104
  - lib/robust_client_socket/http/client.rb
87
105
  - lib/robust_client_socket/http/helpers.rb