"""PDP authorization utilities.""" from ddtrace import tracer from flask import g from python_pdp_sdk import ( ResourceWithAttributes, ) from python_pdp_sdk.backends import exceptions from python_pdp_sdk.resource_getters.base import ForwardKwargsGetter from abacus_account.config import authorization_backend from abacus_account.constants import error @tracer.wrap() def authorize_resource( resource_id: int, resource_type: str, action: str = 'view', ) -> bool: """Authorize a resource with empty attributes.""" authorized = authorization_backend.is_authorized( action=action, resource_id=resource_id, resource_type=resource_type, resource_getter=ForwardKwargsGetter(), ) if not authorized: g.log.warn( error.ERROR_CODE_UNAUTHORIZED_RESOURCE, resources={ 'identity_id': g.request_context.jwt_identity_id, 'resource_id': resource_id, 'resource_type': resource_type, 'auth_response': authorized } ) return False return True @tracer.wrap() def authorize_many_accounts( account_ids: list[int], action: str = 'view_abacus_account_info', ) -> bool: """Authorize many accounts via.""" g.log.debug( 'PP authorize many accounts', resources={ 'identity_id': g.request_context.jwt_identity_id, 'account_ids': account_ids, } ) resources_with_attributes = [ ResourceWithAttributes( resource_id=account_id, attributes={ 'tenant': {'tenant_type': 'account'}, 'id_to_uuid_exchange_tenant': { 'tenant_type': 'account', 'tenant_id': account_id, } }, ) for account_id in account_ids ] try: auth_response = authorization_backend.is_authorized_many( action=action, resource_type='account', resources_with_attributes=resources_with_attributes, ) except exceptions.InvalidRequestException as e: g.log.warn( 'Caught a PDP InvalidRequestException', resources={ 'identity_id': g.request_context.jwt_identity_id, 'resource_ids': account_ids, 'resource_type': 'account', 'error': str(e), } ) return False if len(auth_response) != len(account_ids) or not all(auth_response): g.log.warn( error.ERROR_CODE_UNAUTHORIZED_MANY_ACCOUNTS, resources={ 'identity_id': g.request_context.jwt_identity_id, 'account_ids': account_ids, 'auth_response': auth_response } ) return False return True