19
19
from ansible_base .lib .utils .auth import get_user_by_ansible_id
20
20
from ansible_base .lib .utils .translations import translatableConditionally as _
21
21
from ansible_base .resource_registry .models import Resource , ResourceType
22
+ from ansible_base .resource_registry .rest_client import get_resource_server_client
22
23
from ansible_base .resource_registry .signals .handlers import no_reverse_sync
23
24
24
25
logger = logging .getLogger ("ansible_base.jwt_consumer.common.auth" )
@@ -52,6 +53,7 @@ def __init__(self, user_fields=default_mapped_user_fields) -> None:
52
53
self .cache = JWTCache ()
53
54
self .user = None
54
55
self .token = None
56
+ self .gateway_claims = None # Store claims from gateway
55
57
56
58
@log_excess_runtime (logger , debug_cutoff = 0.01 )
57
59
def parse_jwt_token (self , request ):
@@ -142,10 +144,43 @@ def parse_jwt_token(self, request):
142
144
resource .service_id = self .token ['service_id' ]
143
145
resource .save (update_fields = ['ansible_id' , 'service_id' ])
144
146
147
+ # Fetch JWT claims from gateway service-index (required for RBAC processing)
148
+ user_ansible_id = self .token ['sub' ]
149
+ logger .debug (f"Fetching claims from gateway for user { user_ansible_id } " )
150
+
151
+ jwt_claims = self ._fetch_jwt_claims_from_gateway (user_ansible_id )
152
+
153
+ if jwt_claims :
154
+ self .gateway_claims = jwt_claims
155
+ logger .debug (f"Successfully loaded gateway claims for user { user_ansible_id } " )
156
+ else :
157
+ logger .error (f"Failed to fetch claims from gateway for user { user_ansible_id } . RBAC processing will not be available." )
158
+ # Note: We don't raise an exception here to allow basic authentication to succeed
159
+ # RBAC processing will fail gracefully with appropriate error messages
145
160
setattr (self .user , "resource_api_actions" , self .token .get ("resource_api_actions" , None ))
146
161
147
162
logger .info (f"User { self .user .username } authenticated from JWT auth" )
148
163
164
+ def _fetch_jwt_claims_from_gateway (self , user_ansible_id ):
165
+ """
166
+ Fetch JWT claims for a user from the gateway service-index API.
167
+ Returns None if claims cannot be retrieved.
168
+ """
169
+ try :
170
+ client = get_resource_server_client ("service-index" )
171
+ response = client .get_jwt_claims (user_ansible_id )
172
+
173
+ if response .status_code == 200 :
174
+ claims = response .json ()
175
+ logger .debug (f"Retrieved JWT claims from gateway for user { user_ansible_id } " )
176
+ return claims
177
+ else :
178
+ logger .warning (f"Failed to retrieve JWT claims from gateway for user { user_ansible_id } : " f"{ response .status_code } " )
179
+ return None
180
+ except Exception as e :
181
+ logger .error (f"Error fetching JWT claims from gateway for user { user_ansible_id } : { e } " )
182
+ return None
183
+
149
184
def log_and_raise (self , conditional_translate_object , expand_values = {}, error_code = None ):
150
185
logger .error (conditional_translate_object .not_translated () % expand_values )
151
186
translated_error_message = conditional_translate_object .translated () % expand_values
@@ -226,7 +261,9 @@ def validate_token(self, unencrypted_token, decryption_key, request_id=None):
226
261
return validated_body
227
262
228
263
def decode_jwt_token (self , unencrypted_token , decryption_key , additional_options = {}):
229
- local_required_field = ["sub" , "user_data" , "exp" , "objects" , "object_roles" , "global_roles" , "version" ]
264
+ # Core required fields - objects, object_roles, global_roles are now deprecated
265
+ # and will be loaded from the gateway jwt_claims endpoint instead
266
+ local_required_field = ["sub" , "user_data" , "exp" , "version" ]
230
267
options = {"require" : local_required_field }
231
268
options .update (additional_options )
232
269
return jwt .decode (
@@ -259,16 +296,23 @@ def get_role_definition(self, name: str) -> Optional[Model]:
259
296
def process_rbac_permissions (self ):
260
297
"""
261
298
This is a default process_permissions which should be usable if you are using RBAC from DAB
299
+ Uses gateway claims data exclusively - no fallback to JWT token fields
262
300
"""
263
- if self .token is None or self .user is None :
264
- logger .error ("Unable to process rbac permissions because user or token is not defined, please call authenticate first" )
301
+ if self .user is None :
302
+ logger .error ("Unable to process rbac permissions because user is not defined, please call authenticate first" )
303
+ return
304
+
305
+ if self .gateway_claims is None :
306
+ logger .error ("Unable to process rbac permissions because gateway claims are not available. Ensure gateway jwt_claims endpoint is accessible." )
265
307
return
266
308
267
309
from ansible_base .rbac .models import RoleUserAssignment
268
310
269
311
role_diff = RoleUserAssignment .objects .filter (user = self .user , role_definition__name__in = settings .ANSIBLE_BASE_JWT_MANAGED_ROLES )
270
312
271
- for system_role_name in self .token .get ("global_roles" , []):
313
+ # Process global roles from gateway claims
314
+ global_roles = self .gateway_claims .get ("global_roles" , [])
315
+ for system_role_name in global_roles :
272
316
logger .debug (f"Processing system role { system_role_name } for { self .user .username } " )
273
317
rd = self .get_role_definition (system_role_name )
274
318
if rd :
@@ -282,7 +326,11 @@ def process_rbac_permissions(self):
282
326
logger .error (f"Unable to grant { self .user .username } system level role { system_role_name } because it does not exist" )
283
327
continue
284
328
285
- for object_role_name in self .token .get ('object_roles' , {}).keys ():
329
+ # Process object roles from gateway claims
330
+ object_roles = self .gateway_claims .get ('object_roles' , {})
331
+ objects = self .gateway_claims .get ('objects' , {})
332
+
333
+ for object_role_name in object_roles .keys ():
286
334
rd = self .get_role_definition (object_role_name )
287
335
if rd is None :
288
336
logger .error (f"Unable to grant { self .user .username } object role { object_role_name } because it does not exist" )
@@ -291,11 +339,11 @@ def process_rbac_permissions(self):
291
339
logger .error (f"Unable to grant { self .user .username } object role { object_role_name } because it is not a JWT managed role" )
292
340
continue
293
341
294
- object_type = self . token [ ' object_roles' ] [object_role_name ]['content_type' ]
295
- object_indexes = self . token [ ' object_roles' ] [object_role_name ]['objects' ]
342
+ object_type = object_roles [object_role_name ]['content_type' ]
343
+ object_indexes = object_roles [object_role_name ]['objects' ]
296
344
297
345
for index in object_indexes :
298
- object_data = self . token [ ' objects' ] [object_type ][index ]
346
+ object_data = objects [object_type ][index ]
299
347
try :
300
348
resource , obj = self .get_or_create_resource (object_type , object_data )
301
349
except IntegrityError as e :
@@ -310,7 +358,7 @@ def process_rbac_permissions(self):
310
358
role_diff = role_diff .exclude (pk = assignment .pk )
311
359
logger .info (f"Granted user { self .user .username } role { object_role_name } to object { obj .name } with ansible_id { object_data ['ansible_id' ]} " )
312
360
313
- # Remove all permissions not authorized by the JWT
361
+ # Remove all permissions not authorized by the gateway claims
314
362
for role_assignment in role_diff :
315
363
rd = role_assignment .role_definition
316
364
content_object = role_assignment .content_object
@@ -322,9 +370,17 @@ def process_rbac_permissions(self):
322
370
def get_or_create_resource (self , content_type : str , data : dict ) -> Tuple [Optional [Resource ], Optional [Model ]]:
323
371
"""
324
372
Gets or creates a resource from a content type and its default data
373
+ Uses gateway claims exclusively - no fallback to JWT token fields
325
374
326
375
This can only build or get organizations or teams
376
+ Args:
377
+ content_type: Type of content ('team', 'organization')
378
+ data: Resource data dictionary
327
379
"""
380
+ if self .gateway_claims is None :
381
+ logger .error ("Unable to create resource because gateway claims are not available" )
382
+ return None , None
383
+
328
384
object_ansible_id = data ['ansible_id' ]
329
385
try :
330
386
resource = Resource .objects .get (ansible_id = object_ansible_id )
@@ -337,7 +393,7 @@ def get_or_create_resource(self, content_type: str, data: dict) -> Tuple[Optiona
337
393
if content_type == 'team' :
338
394
# For a team we first have to make sure the org is there
339
395
org_id = data ['org' ]
340
- organization_data = self .token ['objects' ]["organization" ][org_id ]
396
+ organization_data = self .gateway_claims ['objects' ]["organization" ][org_id ]
341
397
342
398
# Now that we have the org we can build a team
343
399
org_resource , _ = self .get_or_create_resource ("organization" , organization_data )
@@ -359,7 +415,7 @@ def get_or_create_resource(self, content_type: str, data: dict) -> Tuple[Optiona
359
415
360
416
return resource , resource .content_object
361
417
else :
362
- logger .error (f"build_resource_stub does not know how to build an object of type { type } " )
418
+ logger .error (f"build_resource_stub does not know how to build an object of type { content_type } " )
363
419
return None , None
364
420
365
421
0 commit comments