jwt_auth_cognito 1.0.0.pre.beta.17 → 1.0.0.pre.beta.18
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 +4 -4
- data/CHANGELOG.md +38 -0
- data/CLAUDE.md +1 -1
- data/README.md +32 -1
- data/jwt_auth_cognito.gemspec +1 -1
- data/lib/jwt_auth_cognito/api_key_validator.rb +44 -5
- data/lib/jwt_auth_cognito/configuration.rb +9 -2
- data/lib/jwt_auth_cognito/redis_service.rb +133 -3
- data/lib/jwt_auth_cognito/version.rb +1 -1
- data/lib/jwt_auth_cognito.rb +3 -0
- metadata +4 -4
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: f6124ee1a2249c9e087eda0106a9a034f71f8128c220b5f3b1ae7a2956a9dd10
|
|
4
|
+
data.tar.gz: c34b3d31bf8496653f1fef86aeddd392a78bbfa466d1bfcec717922de7c775af
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 9be99aaa0faaf0ff000cf3cfdfa1549c993f7581950f2cc44ad7e0feb1e3b85f6dcfbc9cf7f956f4884e5d34afdff8627ac311806a5d27e57d3361ba88ff1a8c
|
|
7
|
+
data.tar.gz: ce2130385f96057013f41a7c35f6849764ebd4631afab24ea0099e5ee4cb905494695217690e6c8ead6c628c7a66806ae8f36d25dc9a5c5cc0f8b6698312adfb
|
data/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,44 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.0.0-beta.18] - 2026-11-30
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- **Usuario ACL de Redis:** `REDIS_USERNAME` (`config.redis_username`, y `username:` en `redis_config` del
|
|
15
|
+
factory). Sin él, Redis autentica la contraseña como el usuario `default`, como hasta ahora. Permite que un
|
|
16
|
+
servicio se conecte con un usuario de privilegios mínimos.
|
|
17
|
+
- **`API_KEY_TRACK_LAST_USED`** (`config.api_key_track_last_used`, por defecto `true`). Con `false`, validar
|
|
18
|
+
una API key no escribe nada en Redis. Es lo que usa un servicio con un usuario de solo lectura.
|
|
19
|
+
- **Log de la blacklist.** Si no se puede consultar, la validación sigue fallando abierta (un token revocado
|
|
20
|
+
pasa, igual que en auth-service), pero ahora queda en el log, como mucho una vez por minuto por proceso.
|
|
21
|
+
Un `NOPERM` (al usuario le falta `+exists ~revoked:*`) se informa aparte como error de configuración. Va a
|
|
22
|
+
`Rails.logger` si existe (`warn` para una caída, `error` para el `NOPERM`); si no, a stderr. Los mensajes no
|
|
23
|
+
incluyen la clave.
|
|
24
|
+
- `REDIS_USERNAME` sin `REDIS_PASSWORD` lanza `ConfigurationError` al conectar: redis-rb ignora el usuario si
|
|
25
|
+
no hay contraseña, y la conexión quedaba como `default`.
|
|
26
|
+
|
|
27
|
+
### Fixed
|
|
28
|
+
|
|
29
|
+
- **`lastUsed` ya no reactiva ni recrea una API key.** Se escribía con un `SET` del JSON leído al validar:
|
|
30
|
+
si auth-service desactivaba o revocaba la key entre la lectura y la escritura, el `SET` volvía a dejar
|
|
31
|
+
`isActive: true` o recreaba la key borrada. Ahora escribe con compare-and-set (el mismo script Lua de
|
|
32
|
+
auth-service, `RedisService#compare_and_set`): solo si el valor sigue siendo el que se leyó.
|
|
33
|
+
- Si Redis responde `NOPERM` al escribir `lastUsed` (usuario de solo lectura con
|
|
34
|
+
`API_KEY_TRACK_LAST_USED` sin apagar), el registro se apaga para el proceso y se avisa una sola vez, en vez
|
|
35
|
+
de fallar y escribir en el log en cada request.
|
|
36
|
+
|
|
37
|
+
- **La API key ya no queda en el log.** Ante una falla de Redis al leer la key, el error incluía
|
|
38
|
+
`api-keys:<la key completa>` y `validate_api_key` lo imprimía. Ahora las claves van enmascaradas (prefijo y
|
|
39
|
+
8 caracteres), de un error de comando de Redis solo se informa la clase, y `validate_api_key` imprime solo la
|
|
40
|
+
clase del error.
|
|
41
|
+
- En Redis 6, la denegación del ACL dentro del script de `lastUsed` también apaga el registro (ahí no llega
|
|
42
|
+
como `NOPERM`).
|
|
43
|
+
|
|
44
|
+
### Changed
|
|
45
|
+
|
|
46
|
+
- **Mínimo de `redis` a `>= 4.3.0`,** la primera versión que acepta `username`.
|
|
47
|
+
|
|
10
48
|
## [1.0.0-beta.17] - 2026-11-04
|
|
11
49
|
|
|
12
50
|
### Changed
|
data/CLAUDE.md
CHANGED
|
@@ -323,7 +323,7 @@ JWKS_CACHE_TTL=3600 # 1 hour
|
|
|
323
323
|
Designed for compatibility with legacy Rails applications:
|
|
324
324
|
- **Ruby**: >= 2.7.0 (compatible with llegando-neo Ruby 2.7.5)
|
|
325
325
|
- **Rails**: >= 5.0 (compatible with llegando-neo Rails 5.2.6)
|
|
326
|
-
- **Redis**: >= 4.
|
|
326
|
+
- **Redis**: >= 4.3.0 (first version with the ACL `username` option; llegando-neo uses 4.5.1)
|
|
327
327
|
|
|
328
328
|
## Publishing and Distribution
|
|
329
329
|
|
data/README.md
CHANGED
|
@@ -79,6 +79,7 @@ COGNITO_CLIENT_SECRET=tu-client-secret
|
|
|
79
79
|
# Configuración de Redis
|
|
80
80
|
REDIS_HOST=localhost
|
|
81
81
|
REDIS_PORT=6379
|
|
82
|
+
REDIS_USERNAME=mi-servicio # Opcional: usuario ACL. Sin él, Redis usa el usuario `default`
|
|
82
83
|
REDIS_PASSWORD=tu-password
|
|
83
84
|
REDIS_DB=0
|
|
84
85
|
REDIS_TLS=true
|
|
@@ -101,6 +102,7 @@ AWS_SSM_ENDPOINT=https://ssm.us-east-1.amazonaws.com # Opcional, para VPC endpo
|
|
|
101
102
|
|
|
102
103
|
# Habilitar funcionalidades específicas
|
|
103
104
|
ENABLE_API_KEY_VALIDATION=true # Validación de API keys
|
|
105
|
+
API_KEY_TRACK_LAST_USED=true # Registrar lastUsed de la API key (false con un usuario de solo lectura)
|
|
104
106
|
ENABLE_USER_DATA_RETRIEVAL=true # Enriquecimiento de datos de usuario
|
|
105
107
|
ENABLE_USER_IDENTITY_ENRICHMENT=true # Enriquecimiento de identidad (email en access tokens)
|
|
106
108
|
IDENTITY_CACHE_TIMEOUT=300 # TTL de caché de identidad por sub (segundos)
|
|
@@ -369,6 +371,35 @@ end
|
|
|
369
371
|
- **App API Keys** (`scope: 'app'`) - Acceso restringido a una aplicación específica
|
|
370
372
|
- **Client API Keys** (`scope: 'client'`) - Para aplicaciones cliente
|
|
371
373
|
|
|
374
|
+
**`lastUsed`:** después de validar, la gema registra `lastUsed` en la key con compare-and-set: solo escribe si el registro sigue siendo el que leyó, así que nunca reactiva ni recrea una key que auth-service desactivó o revocó mientras tanto. Con `API_KEY_TRACK_LAST_USED=false` no escribe nada.
|
|
375
|
+
|
|
376
|
+
### Usuario de Redis de solo lectura (ACL)
|
|
377
|
+
|
|
378
|
+
Un servicio que solo valida tokens y API keys puede conectarse con un usuario ACL de privilegios mínimos en vez del usuario `default` de auth-service:
|
|
379
|
+
|
|
380
|
+
```bash
|
|
381
|
+
REDIS_USERNAME=mi-servicio
|
|
382
|
+
REDIS_PASSWORD=...
|
|
383
|
+
API_KEY_TRACK_LAST_USED=false
|
|
384
|
+
```
|
|
385
|
+
|
|
386
|
+
Permisos que necesita ese usuario (Redis 7, con un selector para que `EXISTS` quede acotado a la blacklist):
|
|
387
|
+
|
|
388
|
+
```
|
|
389
|
+
ACL SETUSER mi-servicio on >... resetkeys -@all +ping +get ~api-keys:* (+exists ~revoked:*)
|
|
390
|
+
```
|
|
391
|
+
|
|
392
|
+
- `+ping`: la gema hace `PING` al abrir cada conexión del pool.
|
|
393
|
+
- `+get ~api-keys:*`: la validación de la API key.
|
|
394
|
+
- `+exists ~revoked:*`: la blacklist de tokens, que se consulta en cada validación.
|
|
395
|
+
- `AUTH` y `HELLO` no hace falta otorgarlos.
|
|
396
|
+
|
|
397
|
+
Con `enable_user_data_retrieval` hace falta además `+get` sobre `user:permissions:*`, `permissions:cache:*`, `app:*`, `org:*`, `app:roles:*` y `app-schemas`.
|
|
398
|
+
|
|
399
|
+
`REDIS_USERNAME` exige `REDIS_PASSWORD`: redis-rb solo se autentica cuando hay contraseña, así que un usuario sin contraseña se conectaría como `default`. En ese caso la gema no se conecta y lanza `ConfigurationError`.
|
|
400
|
+
|
|
401
|
+
Si al usuario le falta `+exists`, Redis responde `NOPERM`, la validación falla abierta (un token revocado pasa) y la gema deja en el log un error de configuración (nivel `error`), como mucho una vez por minuto. Si se deja `API_KEY_TRACK_LAST_USED` en `true` con un usuario de solo lectura, el primer `NOPERM` apaga el registro de `lastUsed` en ese proceso y lo avisa una vez.
|
|
402
|
+
|
|
372
403
|
### Factory Method para Configuración Simplificada (Nuevo v0.3.0)
|
|
373
404
|
|
|
374
405
|
```ruby
|
|
@@ -1118,7 +1149,7 @@ end
|
|
|
1118
1149
|
|
|
1119
1150
|
- **Ruby**: >= 2.7.0 (Compatible con llegando-neo Ruby 2.7.5)
|
|
1120
1151
|
- **Rails**: >= 5.0 (Compatible con llegando-neo Rails 5.2.6)
|
|
1121
|
-
- **Redis**: >= 4.
|
|
1152
|
+
- **Redis**: >= 4.3.0, < 6.0 (4.3.0 es la primera que acepta `username`; llegando-neo usa 4.5.1)
|
|
1122
1153
|
|
|
1123
1154
|
## Desarrollo
|
|
1124
1155
|
|
data/jwt_auth_cognito.gemspec
CHANGED
|
@@ -47,7 +47,7 @@ Gem::Specification.new do |spec|
|
|
|
47
47
|
spec.add_dependency 'connection_pool', '~> 2.2' # Shared, thread-safe Redis connection pool
|
|
48
48
|
spec.add_dependency 'json', '~> 2.0'
|
|
49
49
|
spec.add_dependency 'jwt', '~> 2.0'
|
|
50
|
-
spec.add_dependency 'redis', '>= 4.
|
|
50
|
+
spec.add_dependency 'redis', '>= 4.3.0', '< 6.0' # 4.3.0 adds the ACL `username` option; < 6 for llegando-neo
|
|
51
51
|
|
|
52
52
|
# Development dependencies
|
|
53
53
|
spec.add_development_dependency 'aws-sdk-core', '~> 3.0' # For testing SSM functionality
|
|
@@ -4,6 +4,29 @@ require 'json'
|
|
|
4
4
|
|
|
5
5
|
module JwtAuthCognito
|
|
6
6
|
class ApiKeyValidator
|
|
7
|
+
TRACKING_MUTEX = Mutex.new
|
|
8
|
+
|
|
9
|
+
class << self
|
|
10
|
+
# Set when Redis answered NOPERM to the lastUsed write: the ACL user is read-only,
|
|
11
|
+
# so the process stops trying instead of failing (and logging) on every request.
|
|
12
|
+
def last_used_tracking_disabled?
|
|
13
|
+
TRACKING_MUTEX.synchronize { @last_used_tracking_disabled == true }
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
# Returns true only for the caller that switched it off, so the notice is logged once.
|
|
17
|
+
def disable_last_used_tracking!
|
|
18
|
+
TRACKING_MUTEX.synchronize do
|
|
19
|
+
return false if @last_used_tracking_disabled
|
|
20
|
+
|
|
21
|
+
@last_used_tracking_disabled = true
|
|
22
|
+
end
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def reset_last_used_tracking!
|
|
26
|
+
TRACKING_MUTEX.synchronize { @last_used_tracking_disabled = false }
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
|
|
7
30
|
def initialize(config)
|
|
8
31
|
@config = config
|
|
9
32
|
@redis_service = RedisService.new(config)
|
|
@@ -23,7 +46,7 @@ module JwtAuthCognito
|
|
|
23
46
|
return { valid: false, error: 'API key is inactive' } unless parsed['isActive']
|
|
24
47
|
|
|
25
48
|
# Update last used (fire and forget for performance)
|
|
26
|
-
update_last_used(api_key, parsed)
|
|
49
|
+
update_last_used(api_key, key_data, parsed)
|
|
27
50
|
|
|
28
51
|
{
|
|
29
52
|
valid: true,
|
|
@@ -39,7 +62,8 @@ module JwtAuthCognito
|
|
|
39
62
|
}
|
|
40
63
|
}
|
|
41
64
|
rescue StandardError => e
|
|
42
|
-
|
|
65
|
+
# Only the class: messages from older code paths could carry the key itself.
|
|
66
|
+
puts "Error validating API key: #{e.class}"
|
|
43
67
|
{ valid: false, error: 'API key validation failed' }
|
|
44
68
|
end
|
|
45
69
|
end
|
|
@@ -67,10 +91,25 @@ module JwtAuthCognito
|
|
|
67
91
|
|
|
68
92
|
private
|
|
69
93
|
|
|
70
|
-
|
|
94
|
+
# Records lastUsed with compare-and-set against the exact string read during
|
|
95
|
+
# validation (`raw`): if auth-service deactivated, revoked or otherwise changed the
|
|
96
|
+
# key in between, nothing is written. A plain SET of the re-serialized JSON could
|
|
97
|
+
# bring back `isActive: true` or recreate a revoked key. Mirrors auth-service's
|
|
98
|
+
# ApiKeyManager.updateLastUsed.
|
|
99
|
+
def update_last_used(api_key, raw, parsed)
|
|
100
|
+
return unless @config.api_key_track_last_used
|
|
101
|
+
return if self.class.last_used_tracking_disabled?
|
|
102
|
+
|
|
103
|
+
updated = parsed.merge('lastUsed' => (Time.now.to_f * 1000).to_i).to_json
|
|
71
104
|
Thread.new do
|
|
72
|
-
|
|
73
|
-
|
|
105
|
+
@redis_service.compare_and_set("api-keys:#{api_key}", raw, updated)
|
|
106
|
+
rescue RedisPermissionError
|
|
107
|
+
if self.class.disable_last_used_tracking!
|
|
108
|
+
RedisService.log_warning(
|
|
109
|
+
'[jwt_auth_cognito] The Redis user cannot write API key lastUsed (NOPERM); ' \
|
|
110
|
+
'tracking is off for this process. Set API_KEY_TRACK_LAST_USED=false for a read-only user.'
|
|
111
|
+
)
|
|
112
|
+
end
|
|
74
113
|
rescue StandardError => e
|
|
75
114
|
puts "Error updating last used timestamp: #{e.message}"
|
|
76
115
|
end
|
|
@@ -3,12 +3,12 @@
|
|
|
3
3
|
module JwtAuthCognito
|
|
4
4
|
class Configuration
|
|
5
5
|
attr_accessor :cognito_user_pool_id, :cognito_region, :cognito_client_id, :cognito_client_secret,
|
|
6
|
-
:redis_host, :redis_port, :redis_password, :redis_db,
|
|
6
|
+
:redis_host, :redis_port, :redis_username, :redis_password, :redis_db,
|
|
7
7
|
:redis_ssl, :redis_timeout, :redis_connect_timeout, :redis_read_timeout,
|
|
8
8
|
:redis_ca_cert_path, :redis_ca_cert_name, :redis_verify_mode,
|
|
9
9
|
:redis_pool_size, :redis_pool_timeout,
|
|
10
10
|
:jwks_cache_ttl, :validation_mode, :environment,
|
|
11
|
-
:enable_api_key_validation, :enable_user_data_retrieval,
|
|
11
|
+
:enable_api_key_validation, :enable_user_data_retrieval, :api_key_track_last_used,
|
|
12
12
|
:enable_user_identity_enrichment, :identity_cache_timeout, :identity_attributes
|
|
13
13
|
|
|
14
14
|
def initialize
|
|
@@ -20,6 +20,9 @@ module JwtAuthCognito
|
|
|
20
20
|
# Redis configuration with environment variables
|
|
21
21
|
@redis_host = ENV['REDIS_HOST'] || 'localhost'
|
|
22
22
|
@redis_port = (ENV['REDIS_PORT'] || 6379).to_i
|
|
23
|
+
# Redis ACL user. Without it, Redis authenticates the password as the `default`
|
|
24
|
+
# user. Set it to connect with a least-privilege user (e.g. read-only).
|
|
25
|
+
@redis_username = ENV['REDIS_USERNAME'].to_s.empty? ? nil : ENV.fetch('REDIS_USERNAME', nil)
|
|
23
26
|
@redis_password = ENV.fetch('REDIS_PASSWORD', nil)
|
|
24
27
|
@redis_db = (ENV['REDIS_DB'] || 0).to_i
|
|
25
28
|
@redis_ssl = ENV['REDIS_TLS'] == 'true' || ENV['REDIS_SSL'] == 'true'
|
|
@@ -45,6 +48,10 @@ module JwtAuthCognito
|
|
|
45
48
|
@enable_api_key_validation = ENV['ENABLE_API_KEY_VALIDATION'] == 'true'
|
|
46
49
|
@enable_user_data_retrieval = ENV['ENABLE_USER_DATA_RETRIEVAL'] == 'true'
|
|
47
50
|
|
|
51
|
+
# Record `lastUsed` on the API key after a successful validation. Set it to false
|
|
52
|
+
# when the Redis user is read-only: validation then writes nothing.
|
|
53
|
+
@api_key_track_last_used = ENV['API_KEY_TRACK_LAST_USED'] != 'false'
|
|
54
|
+
|
|
48
55
|
# Cognito identity enrichment: populate payload['email'] (and other identity
|
|
49
56
|
# attributes) for ACCESS tokens via GetUser, since access tokens don't carry them.
|
|
50
57
|
@enable_user_identity_enrichment = ENV['ENABLE_USER_IDENTITY_ENRICHMENT'] == 'true'
|
|
@@ -16,6 +16,25 @@ module JwtAuthCognito
|
|
|
16
16
|
BLACKLIST_PREFIX = 'revoked:'
|
|
17
17
|
USER_TOKENS_PREFIX = 'user_tokens:'
|
|
18
18
|
|
|
19
|
+
# Same script as auth-service's RedisService.compareAndSet (src/utils/redis.ts).
|
|
20
|
+
# ARGV[1] = '1' means "the key must currently hold ARGV[2]"; '0' means "the key
|
|
21
|
+
# must not exist". Writes ARGV[3] only when that holds, so a value read earlier
|
|
22
|
+
# never overwrites a newer one (e.g. an API key deactivated or revoked meanwhile).
|
|
23
|
+
COMPARE_AND_SET_SCRIPT = <<~LUA
|
|
24
|
+
local current = redis.call('GET', KEYS[1])
|
|
25
|
+
if (ARGV[1] == '0' and current == false) or (ARGV[1] == '1' and current == ARGV[2]) then
|
|
26
|
+
redis.call('SET', KEYS[1], ARGV[3])
|
|
27
|
+
return 1
|
|
28
|
+
end
|
|
29
|
+
return 0
|
|
30
|
+
LUA
|
|
31
|
+
|
|
32
|
+
# Minimum seconds between two log lines about the same blacklist failure, per
|
|
33
|
+
# process: the blacklist is read on every validation, so an outage or a missing
|
|
34
|
+
# ACL permission would otherwise write one line per request.
|
|
35
|
+
WARN_INTERVAL_SECONDS = 60
|
|
36
|
+
WARN_MUTEX = Mutex.new
|
|
37
|
+
|
|
19
38
|
# One shared, thread-safe connection pool per process — independent of how many
|
|
20
39
|
# RedisService instances exist (the blacklist, user-data and api-key services each
|
|
21
40
|
# build their own instance, yet they all share this pool). This bounds Redis
|
|
@@ -37,6 +56,70 @@ module JwtAuthCognito
|
|
|
37
56
|
def reset_pool!
|
|
38
57
|
@pool = nil
|
|
39
58
|
end
|
|
59
|
+
|
|
60
|
+
# True when Redis rejected the command because the ACL user lacks permission
|
|
61
|
+
# for it or for the key (NOPERM). redis-rb 5 raises Redis::PermissionError;
|
|
62
|
+
# 4.x raises a plain Redis::CommandError whose message starts with NOPERM.
|
|
63
|
+
def permission_error?(error)
|
|
64
|
+
error.is_a?(Redis::CommandError) && error.message.to_s.start_with?('NOPERM')
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# Redis 6.x reports an ACL denial inside a Lua script as a generic script error
|
|
68
|
+
# ("ERR Error running script ... The user executing the script can't run this
|
|
69
|
+
# command"), not as NOPERM. Redis 7 keeps the NOPERM prefix.
|
|
70
|
+
def script_permission_error?(error)
|
|
71
|
+
permission_error?(error) ||
|
|
72
|
+
(error.is_a?(Redis::CommandError) && error.message.to_s.include?("user executing the script can't run"))
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# Keys may embed secrets (`api-keys:<the API key>`, `revoked:<token suffix>`):
|
|
76
|
+
# keep the prefix and the first 8 characters only.
|
|
77
|
+
def mask_key(key)
|
|
78
|
+
prefix, sep, rest = key.to_s.rpartition(':')
|
|
79
|
+
rest = key.to_s if sep.empty?
|
|
80
|
+
masked = rest.length > 8 ? "#{rest[0, 8]}..." : rest
|
|
81
|
+
sep.empty? ? masked : "#{prefix}#{sep}#{masked}"
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# Redis command errors can quote the key (e.g. NOPERM in Redis 7.2+), so only
|
|
85
|
+
# their class is reported. Connection errors carry host/port, which is useful.
|
|
86
|
+
def error_detail(error)
|
|
87
|
+
error.is_a?(Redis::CommandError) ? error.class.to_s : "#{error.class}: #{error.message}"
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# Logs `message` at most once every WARN_INTERVAL_SECONDS for the same `kind`.
|
|
91
|
+
def warn_throttled(kind, message, level: :warn)
|
|
92
|
+
now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
93
|
+
WARN_MUTEX.synchronize do
|
|
94
|
+
@last_warned_at ||= {}
|
|
95
|
+
last = @last_warned_at[kind]
|
|
96
|
+
return if last && now - last < WARN_INTERVAL_SECONDS
|
|
97
|
+
|
|
98
|
+
@last_warned_at[kind] = now
|
|
99
|
+
end
|
|
100
|
+
level == :error ? log_error(message) : log_warning(message)
|
|
101
|
+
nil
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
def reset_warnings!
|
|
105
|
+
WARN_MUTEX.synchronize { @last_warned_at = {} }
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
def log_warning(message)
|
|
109
|
+
log(:warn, message)
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
def log_error(message)
|
|
113
|
+
log(:error, message)
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
def log(level, message)
|
|
117
|
+
if defined?(Rails) && Rails.respond_to?(:logger) && Rails.logger
|
|
118
|
+
Rails.logger.public_send(level, message)
|
|
119
|
+
else
|
|
120
|
+
Kernel.warn(message)
|
|
121
|
+
end
|
|
122
|
+
end
|
|
40
123
|
end
|
|
41
124
|
|
|
42
125
|
def initialize(config = JwtAuthCognito.configuration)
|
|
@@ -63,11 +146,13 @@ module JwtAuthCognito
|
|
|
63
146
|
key = "#{BLACKLIST_PREFIX}#{token_id}"
|
|
64
147
|
result = with_redis { |redis| redis.exists?(key) }
|
|
65
148
|
result.is_a?(Integer) ? result.positive? : result
|
|
66
|
-
rescue StandardError
|
|
149
|
+
rescue StandardError => e
|
|
67
150
|
# Fail-open graceful degradation: if Redis is unreachable or the pool is
|
|
68
151
|
# exhausted, do not block validation. Mirrors the Node validator and
|
|
69
152
|
# auth-service (RedisService.isTokenRevoked), which also treat errors as
|
|
70
153
|
# "not revoked" so an infrastructure issue never locks every user out.
|
|
154
|
+
# The failure is logged (throttled) so a revoked token passing is visible.
|
|
155
|
+
report_blacklist_failure(e)
|
|
71
156
|
false
|
|
72
157
|
end
|
|
73
158
|
|
|
@@ -124,10 +209,25 @@ module JwtAuthCognito
|
|
|
124
209
|
Base64.strict_encode64(suffix)
|
|
125
210
|
end
|
|
126
211
|
|
|
212
|
+
# Writes `value` only if `key` still holds `expected`. Returns true when it wrote,
|
|
213
|
+
# false when the value changed or the key no longer exists. Raises
|
|
214
|
+
# RedisPermissionError when the ACL user may not run the script (NOPERM). Error
|
|
215
|
+
# messages never include the key: for API keys it is the secret itself.
|
|
216
|
+
def compare_and_set(key, expected, value)
|
|
217
|
+
result = with_redis do |redis|
|
|
218
|
+
redis.eval(COMPARE_AND_SET_SCRIPT, keys: [key], argv: ['1', expected, value])
|
|
219
|
+
end
|
|
220
|
+
result == 1
|
|
221
|
+
rescue Redis::BaseError => e
|
|
222
|
+
raise RedisPermissionError, 'Redis user lacks permission for compare-and-set (EVAL/SET)' if self.class.script_permission_error?(e)
|
|
223
|
+
|
|
224
|
+
raise BlacklistError, "Failed to compare-and-set: #{e.class}"
|
|
225
|
+
end
|
|
226
|
+
|
|
127
227
|
def get(key)
|
|
128
228
|
with_redis { |redis| redis.get(key) }
|
|
129
229
|
rescue Redis::BaseError => e
|
|
130
|
-
raise BlacklistError, "Failed to get key '#{key}': #{e
|
|
230
|
+
raise BlacklistError, "Failed to get key '#{self.class.mask_key(key)}': #{self.class.error_detail(e)}"
|
|
131
231
|
end
|
|
132
232
|
|
|
133
233
|
def set(key, value, ttl = nil)
|
|
@@ -143,11 +243,31 @@ module JwtAuthCognito
|
|
|
143
243
|
end
|
|
144
244
|
true
|
|
145
245
|
rescue Redis::BaseError => e
|
|
146
|
-
raise BlacklistError, "Failed to set key '#{key}': #{e
|
|
246
|
+
raise BlacklistError, "Failed to set key '#{self.class.mask_key(key)}': #{self.class.error_detail(e)}"
|
|
147
247
|
end
|
|
148
248
|
|
|
149
249
|
private
|
|
150
250
|
|
|
251
|
+
def report_blacklist_failure(error)
|
|
252
|
+
if self.class.permission_error?(error)
|
|
253
|
+
# Configuration error, not an outage: it will not fix itself. The Redis message
|
|
254
|
+
# is not logged because it names the key, which carries part of the token.
|
|
255
|
+
self.class.warn_throttled(
|
|
256
|
+
:blacklist_noperm,
|
|
257
|
+
'[jwt_auth_cognito] ERROR: the Redis user cannot read the token blacklist ' \
|
|
258
|
+
"(NOPERM on EXISTS #{BLACKLIST_PREFIX}*). Revoked tokens are being accepted. " \
|
|
259
|
+
"Grant '+exists ~#{BLACKLIST_PREFIX}*' to the Redis user.",
|
|
260
|
+
level: :error
|
|
261
|
+
)
|
|
262
|
+
else
|
|
263
|
+
self.class.warn_throttled(
|
|
264
|
+
:blacklist_unavailable,
|
|
265
|
+
'[jwt_auth_cognito] WARN: token blacklist unavailable, failing open (revoked tokens pass) - ' \
|
|
266
|
+
"#{self.class.error_detail(error)}"
|
|
267
|
+
)
|
|
268
|
+
end
|
|
269
|
+
end
|
|
270
|
+
|
|
151
271
|
# Checks out a connection from the shared pool for the duration of the block.
|
|
152
272
|
# The pool is built lazily on first use and reused across all instances.
|
|
153
273
|
def with_redis(&block)
|
|
@@ -192,6 +312,16 @@ module JwtAuthCognito
|
|
|
192
312
|
read_timeout: @config.redis_read_timeout
|
|
193
313
|
}
|
|
194
314
|
|
|
315
|
+
# ACL user (redis-rb >= 4.3). Without it Redis authenticates as `default`.
|
|
316
|
+
if @config.redis_username
|
|
317
|
+
# redis-rb only sends AUTH when there is a password: a username alone would be
|
|
318
|
+
# silently ignored and the connection would run as `default`.
|
|
319
|
+
unless @config.redis_password && !@config.redis_password.to_s.empty?
|
|
320
|
+
raise ConfigurationError, 'REDIS_USERNAME is set but REDIS_PASSWORD is empty: refusing to connect as the default user'
|
|
321
|
+
end
|
|
322
|
+
|
|
323
|
+
options[:username] = @config.redis_username
|
|
324
|
+
end
|
|
195
325
|
options[:password] = @config.redis_password if @config.redis_password
|
|
196
326
|
|
|
197
327
|
# Enhanced TLS configuration (matching Node.js implementation)
|
data/lib/jwt_auth_cognito.rb
CHANGED
|
@@ -27,6 +27,8 @@ module JwtAuthCognito
|
|
|
27
27
|
class TokenRevokedError < ValidationError; end
|
|
28
28
|
class JWKSError < ValidationError; end
|
|
29
29
|
class RedisConnectionError < BlacklistError; end
|
|
30
|
+
# The Redis ACL user lacks permission for the command or key (NOPERM).
|
|
31
|
+
class RedisPermissionError < BlacklistError; end
|
|
30
32
|
|
|
31
33
|
# Configure the gem
|
|
32
34
|
def self.configure
|
|
@@ -63,6 +65,7 @@ module JwtAuthCognito
|
|
|
63
65
|
# Apply Redis configuration
|
|
64
66
|
config.redis_host = redis_config[:host] if redis_config[:host]
|
|
65
67
|
config.redis_port = redis_config[:port] if redis_config[:port]
|
|
68
|
+
config.redis_username = redis_config[:username] if redis_config[:username]
|
|
66
69
|
config.redis_password = redis_config[:password] if redis_config[:password]
|
|
67
70
|
config.redis_ssl = redis_config[:tls] if redis_config.key?(:tls)
|
|
68
71
|
config.redis_ca_cert_path = redis_config[:ca_cert_path] if redis_config[:ca_cert_path]
|
metadata
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: jwt_auth_cognito
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 1.0.0.pre.beta.
|
|
4
|
+
version: 1.0.0.pre.beta.18
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- The Optimal
|
|
8
8
|
autorequire:
|
|
9
9
|
bindir: exe
|
|
10
10
|
cert_chain: []
|
|
11
|
-
date: 2026-11-
|
|
11
|
+
date: 2026-11-30 00:00:00.000000000 Z
|
|
12
12
|
dependencies:
|
|
13
13
|
- !ruby/object:Gem::Dependency
|
|
14
14
|
name: aws-sdk-cognitoidentityprovider
|
|
@@ -86,7 +86,7 @@ dependencies:
|
|
|
86
86
|
requirements:
|
|
87
87
|
- - ">="
|
|
88
88
|
- !ruby/object:Gem::Version
|
|
89
|
-
version: 4.
|
|
89
|
+
version: 4.3.0
|
|
90
90
|
- - "<"
|
|
91
91
|
- !ruby/object:Gem::Version
|
|
92
92
|
version: '6.0'
|
|
@@ -96,7 +96,7 @@ dependencies:
|
|
|
96
96
|
requirements:
|
|
97
97
|
- - ">="
|
|
98
98
|
- !ruby/object:Gem::Version
|
|
99
|
-
version: 4.
|
|
99
|
+
version: 4.3.0
|
|
100
100
|
- - "<"
|
|
101
101
|
- !ruby/object:Gem::Version
|
|
102
102
|
version: '6.0'
|