jwt_auth_cognito 1.0.0.pre.beta.15 → 1.0.0.pre.beta.17

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: 5478b2beaffce3e103aa915b73735e2b78ae39d4f802fb663fd0aad79a721207
4
- data.tar.gz: 2023c50ebe2234f58243820118edce9e8d413dc348b0798642e4378adc356898
3
+ metadata.gz: d3b9aff743cc56073ce2fdd85d423b41e3f862818f20a8b81e87354e8b0d8974
4
+ data.tar.gz: 30b6434fea7d36b58cffb68ce704bd241c0ac0de7129c0b0d44e0439b07c7c7c
5
5
  SHA512:
6
- metadata.gz: e8a0c2b0bb5897f15bc83b065ccfa060f18d509788cd1406325792caa74ac1d23bc9910c4c81d3f1c4923e21efd6aa0e35655bffb8f44dc1f74767a3ed3e51d9
7
- data.tar.gz: 5bbb8e162f0150c06730a8c63723e6458b50f32404bc12661622d8b670fa3901f1dac9c93a909d59f77d7f63ff0e1d2b9592c2df69247feb9b9b3aac5786db1b
6
+ metadata.gz: d9627fbb19a256d75bfcdbac47f09fc0d33271aeb361587207203bd5894b6771d52f17ce92d7e36c778c43d6cb2387afe496a138d1c0477e9eb5275228fb6f89
7
+ data.tar.gz: 761c0a626904e465dc000cb483e5d913589d7c39caf741a27e6ab1d54fa304736d0e981968e5e5c1403c97383689f132260839fb2a67dc86be9eacdf68f0b1d2
data/CHANGELOG.md CHANGED
@@ -7,7 +7,42 @@ 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.16] - 2026-06-25
10
+ ## [1.0.0-beta.17] - 2026-11-04
11
+
12
+ ### Changed
13
+
14
+ - **BREAKING: `get_access_scope` falla cerrado.** Devuelve `nil` si el usuario no tiene una asignación
15
+ activa en la organización, y lanza un error si no se pueden leer sus permisos o sus roles, si el
16
+ registro está corrupto (`JSON::ParserError`) o si la lectura de datos de usuario no está habilitada
17
+ (`ConfigurationError`). Antes devolvía `{}` en todos esos casos, y `{}` significa "sin restricción":
18
+ un usuario ajeno a la organización, o cualquiera durante una caída de Redis, quedaba sin filtro.
19
+ **Hay que revisar cada llamador:** tratar `nil` como acceso denegado y un error como 503.
20
+
21
+ ### Added
22
+
23
+ - **Un administrador de organización no tiene scope.** Si los roles vigentes y activos o los permisos
24
+ directos del usuario otorgan `org:users:manage` u `org:roles:assign`, también por comodín,
25
+ `get_access_scope` devuelve `{}`, aunque tenga scope propio, scope por defecto de otro rol o
26
+ `resourceRestrictions`. Es la regla de auth-service (`/user/navigation` y `/validate`).
27
+
28
+ ### Fixed
29
+
30
+ - `resolve_access_scope` lee los roles aunque `include_roles` esté apagado: sin eso se perdía el scope
31
+ por defecto de los roles, y no se podría detectar a un admin. Con `include_roles: false` suma una
32
+ lectura de Redis cuando el caché no tiene los roles.
33
+ - Un rol sin `isActive: true` ya no aporta scope, igual que en auth-service. Antes solo se descartaba
34
+ con `isActive: false`.
35
+
36
+ ## [1.0.0-beta.16] - 2026-07-06
37
+
38
+ ### Added
39
+
40
+ - **`organizationUuid` in `user_organizations`.** `#get_user_organizations` (and therefore
41
+ the enriched validation result) now passes through the `organizationUuid` snapshot that
42
+ auth-service denormalizes into `user:permissions:{sub}` when the owning app registers a
43
+ stable UUID for an organization (anti-IDOR initiative). The field is optional and only
44
+ present when the org has one registered; `organizationId` remains the authorization key
45
+ and the value used in RabbitMQ routing keys. No extra Redis reads are performed.
11
46
 
12
47
  ### Fixed
13
48
 
data/README.md CHANGED
@@ -502,6 +502,27 @@ blacklist_service.add_to_blacklist(token, user_id: 'usuario-123')
502
502
  result = jwks_service.validate_token_with_jwks(token)
503
503
  ```
504
504
 
505
+ ## Scope de acceso (ABAC): `get_access_scope`
506
+
507
+ ```ruby
508
+ scope = validator.get_access_scope(user_id, app_id, organization_id)
509
+
510
+ # nil = sin asignación activa en la organización: denegar.
511
+ # {} = sin restricción.
512
+ # Si no, filtrar por recurso: scope['vehicles:read'] => { 'match' =>, 'include' =>, 'exclude' => }
513
+ ```
514
+
515
+ | Resultado | Significado | Qué debe hacer la app |
516
+ |---|---|---|
517
+ | `nil` | El usuario no tiene una asignación activa en la organización | Denegar el acceso |
518
+ | `{}` | Sin restricción. Un administrador de organización siempre recibe `{}` | Mostrar todos los datos |
519
+ | Hash con claves | Scope por `<recurso>:<acción>` | Filtrar con `match`, `include` y `exclude` |
520
+ | 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 `{}` |
521
+
522
+ Un usuario es administrador de organización si sus roles vigentes y activos o sus permisos directos
523
+ otorgan `org:users:manage` u `org:roles:assign`, también por comodín. Es la misma regla de
524
+ `/user/navigation` y `/validate` en auth-service.
525
+
505
526
  ## Modos de Validación
506
527
 
507
528
  ### Modo Seguro (Producción)
@@ -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)
@@ -287,6 +287,8 @@ module JwtAuthCognito
287
287
  'status' => org_data['status']
288
288
  }
289
289
 
290
+ # UUID estable de la org (snapshot denormalizado por auth-service, si la app lo registro)
291
+ user_org['organizationUuid'] = org_data['organizationUuid'] if org_data['organizationUuid']
290
292
  user_org['effectivePermissions'] = effective_permissions if effective_permissions
291
293
 
292
294
  user_organizations << user_org
@@ -353,34 +355,37 @@ module JwtAuthCognito
353
355
  # = union of role default accessScope (R2) + user accessScope (override/extend)
354
356
  # + legacy resourceRestrictions (= include without match).
355
357
  # Keyed by "<resourceType>:<action>" (R3). Expired roles (roleExpiry) are skipped (R1).
356
- # 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.
357
366
  def resolve_access_scope(user_id, app_id, organization_id)
358
367
  raw = @redis_service.get("user:permissions:#{user_id}")
359
- return {} unless raw
368
+ return nil unless raw
360
369
 
361
370
  data = JSON.parse(raw)
362
371
  org_perms = data.dig('permissions', app_id, organization_id)
363
- return {} unless org_perms.is_a?(Hash) && org_perms['status'] == 'active'
372
+ return nil unless org_perms.is_a?(Hash) && org_perms['status'] == 'active'
364
373
 
365
374
  now = (Time.now.to_f * 1000).to_i
366
375
  expiry = org_perms['roleExpiry'].is_a?(Hash) ? org_perms['roleExpiry'] : {}
367
376
  roles = org_perms['roles'].is_a?(Array) ? org_perms['roles'] : []
368
377
  active_roles = roles.reject { |role_id| expiry[role_id] && expiry[role_id] <= now }
369
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
+
370
385
  effective = {}
371
386
 
372
387
  # 1) Role default scope (R2)
373
- unless active_roles.empty?
374
- app_roles = get_app_roles(app_id, organization_id)
375
- app_roles = {} unless app_roles.is_a?(Hash)
376
- active_roles.each do |role_id|
377
- role = app_roles[role_id]
378
- next unless role.is_a?(Hash)
379
- next if role['isActive'] == false
380
-
381
- merge_scope_into(effective, role['accessScope'])
382
- end
383
- end
388
+ current_roles.each { |role| merge_scope_into(effective, role['accessScope']) }
384
389
 
385
390
  # 2) User override/extend (R2)
386
391
  merge_scope_into(effective, org_perms['accessScope'])
@@ -394,9 +399,6 @@ module JwtAuthCognito
394
399
  end
395
400
 
396
401
  effective
397
- rescue StandardError => e
398
- puts "Error resolving access scope for #{user_id}:#{app_id}:#{organization_id}: #{e.message}"
399
- {}
400
402
  end
401
403
 
402
404
  # Resolve permissions the user has over a specific resource instance (ReBAC).
@@ -452,6 +454,27 @@ module JwtAuthCognito
452
454
  @cache_timestamps[key] = Time.now.to_i
453
455
  end
454
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
+
455
478
  # Additively merge a scope map into another: union match per dimension, and include/exclude.
456
479
  def merge_scope_into(into, from)
457
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.15'
4
+ VERSION = '1.0.0-beta.17'
5
5
  end
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.15
4
+ version: 1.0.0.pre.beta.17
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-06-26 00:00:00.000000000 Z
11
+ date: 2026-11-04 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: aws-sdk-cognitoidentityprovider