jwt_auth_cognito 1.0.0.pre.beta.16 → 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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b267346dfc24c4ca838329a29fdeed3191825dd019b4993375fd3627b343c0c1
4
- data.tar.gz: 81d5368d0c5a605e93a1d54c92bd47cfa2ea71abacd6c43e81bb95736dd15e9b
3
+ metadata.gz: f6124ee1a2249c9e087eda0106a9a034f71f8128c220b5f3b1ae7a2956a9dd10
4
+ data.tar.gz: c34b3d31bf8496653f1fef86aeddd392a78bbfa466d1bfcec717922de7c775af
5
5
  SHA512:
6
- metadata.gz: f4add1eff2ee4a65fb744bc7767aaff5fe54147dcd1976df35dcc5d7610e9370f6ec44f3570c0c8e21ecd92809b38ac8dfff12d03cd8c6491e35576a133eb2d7
7
- data.tar.gz: fcf204c00c1596f813b795d0241bcc4117643da1c62256cad409cc7e78f337ddf691df5fecbf94ebb4acbe2f5958d05680b510a720584721bac2e8535f9740ab
6
+ metadata.gz: 9be99aaa0faaf0ff000cf3cfdfa1549c993f7581950f2cc44ad7e0feb1e3b85f6dcfbc9cf7f956f4884e5d34afdff8627ac311806a5d27e57d3361ba88ff1a8c
7
+ data.tar.gz: ce2130385f96057013f41a7c35f6849764ebd4631afab24ea0099e5ee4cb905494695217690e6c8ead6c628c7a66806ae8f36d25dc9a5c5cc0f8b6698312adfb
data/CHANGELOG.md CHANGED
@@ -7,6 +7,70 @@ 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
+
48
+ ## [1.0.0-beta.17] - 2026-11-04
49
+
50
+ ### Changed
51
+
52
+ - **BREAKING: `get_access_scope` falla cerrado.** Devuelve `nil` si el usuario no tiene una asignación
53
+ activa en la organización, y lanza un error si no se pueden leer sus permisos o sus roles, si el
54
+ registro está corrupto (`JSON::ParserError`) o si la lectura de datos de usuario no está habilitada
55
+ (`ConfigurationError`). Antes devolvía `{}` en todos esos casos, y `{}` significa "sin restricción":
56
+ un usuario ajeno a la organización, o cualquiera durante una caída de Redis, quedaba sin filtro.
57
+ **Hay que revisar cada llamador:** tratar `nil` como acceso denegado y un error como 503.
58
+
59
+ ### Added
60
+
61
+ - **Un administrador de organización no tiene scope.** Si los roles vigentes y activos o los permisos
62
+ directos del usuario otorgan `org:users:manage` u `org:roles:assign`, también por comodín,
63
+ `get_access_scope` devuelve `{}`, aunque tenga scope propio, scope por defecto de otro rol o
64
+ `resourceRestrictions`. Es la regla de auth-service (`/user/navigation` y `/validate`).
65
+
66
+ ### Fixed
67
+
68
+ - `resolve_access_scope` lee los roles aunque `include_roles` esté apagado: sin eso se perdía el scope
69
+ por defecto de los roles, y no se podría detectar a un admin. Con `include_roles: false` suma una
70
+ lectura de Redis cuando el caché no tiene los roles.
71
+ - Un rol sin `isActive: true` ya no aporta scope, igual que en auth-service. Antes solo se descartaba
72
+ con `isActive: false`.
73
+
10
74
  ## [1.0.0-beta.16] - 2026-07-06
11
75
 
12
76
  ### Added
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.2.5 (matches llegando-neo Redis version constraints)
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
@@ -502,6 +533,27 @@ blacklist_service.add_to_blacklist(token, user_id: 'usuario-123')
502
533
  result = jwks_service.validate_token_with_jwks(token)
503
534
  ```
504
535
 
536
+ ## Scope de acceso (ABAC): `get_access_scope`
537
+
538
+ ```ruby
539
+ scope = validator.get_access_scope(user_id, app_id, organization_id)
540
+
541
+ # nil = sin asignación activa en la organización: denegar.
542
+ # {} = sin restricción.
543
+ # Si no, filtrar por recurso: scope['vehicles:read'] => { 'match' =>, 'include' =>, 'exclude' => }
544
+ ```
545
+
546
+ | Resultado | Significado | Qué debe hacer la app |
547
+ |---|---|---|
548
+ | `nil` | El usuario no tiene una asignación activa en la organización | Denegar el acceso |
549
+ | `{}` | Sin restricción. Un administrador de organización siempre recibe `{}` | Mostrar todos los datos |
550
+ | Hash con claves | Scope por `<recurso>:<acción>` | Filtrar con `match`, `include` y `exclude` |
551
+ | Lanza un error | Falló la lectura de Redis, el registro está corrupto o la lectura de datos de usuario no está habilitada | Responder 503, nunca tratarlo como `{}` |
552
+
553
+ Un usuario es administrador de organización si sus roles vigentes y activos o sus permisos directos
554
+ otorgan `org:users:manage` u `org:roles:assign`, también por comodín. Es la misma regla de
555
+ `/user/navigation` y `/validate` en auth-service.
556
+
505
557
  ## Modos de Validación
506
558
 
507
559
  ### Modo Seguro (Producción)
@@ -1097,7 +1149,7 @@ end
1097
1149
 
1098
1150
  - **Ruby**: >= 2.7.0 (Compatible con llegando-neo Ruby 2.7.5)
1099
1151
  - **Rails**: >= 5.0 (Compatible con llegando-neo Rails 5.2.6)
1100
- - **Redis**: >= 4.2.5 (Compatible con llegando-neo redis >= 4.2.5)
1152
+ - **Redis**: >= 4.3.0, < 6.0 (4.3.0 es la primera que acepta `username`; llegando-neo usa 4.5.1)
1101
1153
 
1102
1154
  ## Desarrollo
1103
1155
 
@@ -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.2.5', '< 6.0' # Compatible with llegando-neo redis version
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
- puts "Error validating API key: #{e.message}"
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
- def update_last_used(api_key, key_data)
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
- key_data['lastUsed'] = (Time.now.to_f * 1000).to_i
73
- @redis_service.set("api-keys:#{api_key}", key_data.to_json)
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'
@@ -307,9 +307,16 @@ module JwtAuthCognito
307
307
 
308
308
  # Resolve the user's effective ABAC access scope for (app, org).
309
309
  # Hash keyed by "<resourceType>:<action>" => { 'match' =>, 'include' =>, 'exclude' => }.
310
- # The consuming app filters its data with this. Returns {} when there is no scope.
310
+ # The consuming app filters its data with this.
311
+ #
312
+ # Returns nil when the user has no active assignment in the organization: the app must deny
313
+ # access. Returns {} when there is no scope, which means unrestricted access; an organization
314
+ # admin always gets {}.
315
+ #
316
+ # Raises when user data retrieval is not enabled or the permissions cannot be read: the app
317
+ # must not treat that as {}.
311
318
  def get_access_scope(user_id, app_id, org_id)
312
- return {} unless @user_data_service
319
+ raise ConfigurationError, 'User data service not enabled' unless @user_data_service
313
320
 
314
321
  @user_data_service.resolve_access_scope(user_id, app_id, org_id)
315
322
  end
@@ -2,6 +2,15 @@
2
2
 
3
3
  module JwtAuthCognito
4
4
  module PermissionChecker
5
+ # Capabilities that make a user an organization admin (those of the `org-admin` role).
6
+ # Same list as auth-service (ORG_ADMIN_CAPABILITIES in src/utils/orgCapabilities.ts).
7
+ ORG_ADMIN_CAPABILITIES = %w[org:users:manage org:roles:assign].freeze
8
+
9
+ # Does the list grant an organization admin capability? Wildcards count.
10
+ def self.grants_org_admin_capability?(permission_list)
11
+ ORG_ADMIN_CAPABILITIES.any? { |capability| permission_in_list?(capability, permission_list) }
12
+ end
13
+
5
14
  # Checks whether a permission string is satisfied by any entry in permission_list.
6
15
  # Supports wildcard patterns:
7
16
  # * — global wildcard (matches everything)
@@ -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.message}"
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.message}"
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)
@@ -355,34 +355,37 @@ module JwtAuthCognito
355
355
  # = union of role default accessScope (R2) + user accessScope (override/extend)
356
356
  # + legacy resourceRestrictions (= include without match).
357
357
  # Keyed by "<resourceType>:<action>" (R3). Expired roles (roleExpiry) are skipped (R1).
358
- # Returns {} when there is no scope (open access to everything).
358
+ #
359
+ # Returns:
360
+ # - nil when the user has no active assignment in the organization: deny access.
361
+ # - {} when the user is active and has no scope, which means unrestricted access. An
362
+ # organization admin always gets {}, as in auth-service: they see their whole organization.
363
+ #
364
+ # Read failures propagate. {} means "no restriction", so returning it on an error would open
365
+ # the data precisely when the permissions cannot be read.
359
366
  def resolve_access_scope(user_id, app_id, organization_id)
360
367
  raw = @redis_service.get("user:permissions:#{user_id}")
361
- return {} unless raw
368
+ return nil unless raw
362
369
 
363
370
  data = JSON.parse(raw)
364
371
  org_perms = data.dig('permissions', app_id, organization_id)
365
- return {} unless org_perms.is_a?(Hash) && org_perms['status'] == 'active'
372
+ return nil unless org_perms.is_a?(Hash) && org_perms['status'] == 'active'
366
373
 
367
374
  now = (Time.now.to_f * 1000).to_i
368
375
  expiry = org_perms['roleExpiry'].is_a?(Hash) ? org_perms['roleExpiry'] : {}
369
376
  roles = org_perms['roles'].is_a?(Array) ? org_perms['roles'] : []
370
377
  active_roles = roles.reject { |role_id| expiry[role_id] && expiry[role_id] <= now }
371
378
 
379
+ app_roles = active_roles.empty? ? {} : read_app_roles_strict(app_id, organization_id)
380
+ current_roles = active_roles.map { |role_id| app_roles[role_id] }
381
+ .select { |role| role.is_a?(Hash) && role['isActive'] }
382
+
383
+ return {} if org_admin?(org_perms, current_roles)
384
+
372
385
  effective = {}
373
386
 
374
387
  # 1) Role default scope (R2)
375
- unless active_roles.empty?
376
- app_roles = get_app_roles(app_id, organization_id)
377
- app_roles = {} unless app_roles.is_a?(Hash)
378
- active_roles.each do |role_id|
379
- role = app_roles[role_id]
380
- next unless role.is_a?(Hash)
381
- next if role['isActive'] == false
382
-
383
- merge_scope_into(effective, role['accessScope'])
384
- end
385
- end
388
+ current_roles.each { |role| merge_scope_into(effective, role['accessScope']) }
386
389
 
387
390
  # 2) User override/extend (R2)
388
391
  merge_scope_into(effective, org_perms['accessScope'])
@@ -396,9 +399,6 @@ module JwtAuthCognito
396
399
  end
397
400
 
398
401
  effective
399
- rescue StandardError => e
400
- puts "Error resolving access scope for #{user_id}:#{app_id}:#{organization_id}: #{e.message}"
401
- {}
402
402
  end
403
403
 
404
404
  # Resolve permissions the user has over a specific resource instance (ReBAC).
@@ -454,6 +454,27 @@ module JwtAuthCognito
454
454
  @cache_timestamps[key] = Time.now.to_i
455
455
  end
456
456
 
457
+ # Same calculation as auth-service: current, active roles + direct permissions.
458
+ def org_admin?(org_perms, current_roles)
459
+ direct = org_perms['directPermissions'].is_a?(Array) ? org_perms['directPermissions'] : []
460
+ from_roles = current_roles.flat_map { |role| role['permissions'].is_a?(Array) ? role['permissions'] : [] }
461
+ PermissionChecker.grants_org_admin_capability?(direct + from_roles)
462
+ end
463
+
464
+ # Like get_app_roles, but read errors propagate and it does not depend on :include_roles:
465
+ # the scope needs the roles whether or not the enriched result includes them.
466
+ def read_app_roles_strict(app_id, organization_id)
467
+ cached = get_from_cache("app_roles:#{app_id}:#{organization_id}")
468
+ return cached if cached
469
+
470
+ raw = @redis_service.get("app:roles:#{app_id}:#{organization_id}")
471
+ return {} unless raw
472
+
473
+ roles = JSON.parse(raw)
474
+ set_in_cache("app_roles:#{app_id}:#{organization_id}", roles)
475
+ roles
476
+ end
477
+
457
478
  # Additively merge a scope map into another: union match per dimension, and include/exclude.
458
479
  def merge_scope_into(into, from)
459
480
  return unless from.is_a?(Hash)
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module JwtAuthCognito
4
- VERSION = '1.0.0-beta.16'
4
+ VERSION = '1.0.0-beta.18'
5
5
  end
@@ -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.16
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-07-06 00:00:00.000000000 Z
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.2.5
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.2.5
99
+ version: 4.3.0
100
100
  - - "<"
101
101
  - !ruby/object:Gem::Version
102
102
  version: '6.0'