jwt_auth_cognito 1.0.0.pre.beta.16 → 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: b267346dfc24c4ca838329a29fdeed3191825dd019b4993375fd3627b343c0c1
4
- data.tar.gz: 81d5368d0c5a605e93a1d54c92bd47cfa2ea71abacd6c43e81bb95736dd15e9b
3
+ metadata.gz: d3b9aff743cc56073ce2fdd85d423b41e3f862818f20a8b81e87354e8b0d8974
4
+ data.tar.gz: 30b6434fea7d36b58cffb68ce704bd241c0ac0de7129c0b0d44e0439b07c7c7c
5
5
  SHA512:
6
- metadata.gz: f4add1eff2ee4a65fb744bc7767aaff5fe54147dcd1976df35dcc5d7610e9370f6ec44f3570c0c8e21ecd92809b38ac8dfff12d03cd8c6491e35576a133eb2d7
7
- data.tar.gz: fcf204c00c1596f813b795d0241bcc4117643da1c62256cad409cc7e78f337ddf691df5fecbf94ebb4acbe2f5958d05680b510a720584721bac2e8535f9740ab
6
+ metadata.gz: d9627fbb19a256d75bfcdbac47f09fc0d33271aeb361587207203bd5894b6771d52f17ce92d7e36c778c43d6cb2387afe496a138d1c0477e9eb5275228fb6f89
7
+ data.tar.gz: 761c0a626904e465dc000cb483e5d913589d7c39caf741a27e6ab1d54fa304736d0e981968e5e5c1403c97383689f132260839fb2a67dc86be9eacdf68f0b1d2
data/CHANGELOG.md CHANGED
@@ -7,6 +7,32 @@ 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.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
+
10
36
  ## [1.0.0-beta.16] - 2026-07-06
11
37
 
12
38
  ### Added
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)
@@ -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.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.16
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-07-06 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