def _Validations(self, request, context): try: metadata = context.invocation_metadata() token_validator = TokenValidator(context, metadata) LOG.info("Model Name %s", request.model_spec.name) LOG.info("Start of validating token") token_result = True #token_validator.validate_token() if request.model_spec.name != self.model.model_name: LOG.error("Model spec name and model env name does not match") context.set_code(grpc.StatusCode.UNIMPLEMENTED) raise NotImplementedError( 'Model spec name and model env does not match' + str('Model spec name' + request.model_spec.name)) return False if request.model_spec.name is None: LOG.error("Model spec name and model env name does not match") context.set_code(grpc.StatusCode.UNIMPLEMENTED) raise NotImplementedError('Given Model Not Loaded' + str('Model spec name' + request.model_spec.name)) return False if token_result is True: LOG.info('token validated successfully') context.set_code(grpc.StatusCode.OK) context.set_details(self.model.model_name) return True return False except SecurityError as se: s = getattr(se, 'message', str(se)) raise SecurityError(s) return False
def _validate_scopes(scope_list, scopes=None, scope_regex=None): if scopes: scopes_in_token = set(scope_list) if any(expected_scope not in scopes_in_token for expected_scope in scopes): raise SecurityError('Invalid scope: {}'.format(scopes), code=401) elif scope_regex: scopes_in_token = scope_list assert len(scope_regex) == len(scopes_in_token), \ 'Number of scopes in token should match number of validation scope_regex.' assert isinstance(scope_regex, list) and len(scope_regex) in (1, 2) for scope_in_token in scopes_in_token: if bool(re.match(scope_regex[-1], scope_in_token)): scope_regex.pop() elif bool(re.match(scope_regex[0], scope_in_token)): scope_regex.pop(0) else: raise SecurityError( 'Invalid scope regex: {}'.format(scope_regex), code=401)
def retrieve_foundation_service_token(): """ To retrieve new token from uaa credentials configured for foundation service instance. :return: new `access_token` retrieved from given UAA credentials :raises SecurityError: If unable to retrieve new token """ uaa_creds = retrieve_foundation_service_uaa_credentials() if not uaa_creds: raise SecurityError( 'UAA credentials for foundation service is missing', code=500) try: token_manager = JWTTokenManager(base_url=uaa_creds.base_url) access_token = token_manager.retrieve_token_str(uaa_creds, use_cache=False) return access_token except Exception as err: raise SecurityError('Unable to retrieve new token.' + str(err), root_cause=err, code=getattr(err, 'code', 401)) from err
def validate_scopes(self, access_token, scopes=None, scope_regex=None): try: _, encoded_payload, _ = self._split_header_payload_signature_from_token( access_token) json_payload = TokenManager.load_decoded_content_as_json( encoded_payload) JWTTokenManager._validate_scopes_in_payload( json_payload, scopes=scopes, scope_regex=scope_regex) return True, access_token except Exception as err: raise SecurityError('Unable to validate scopes.', root_cause=err, code=getattr(err, 'code', 401)) from err
def _validate_token_against_public_key(self, access_token, public_key): header, encoded_payload, signature = self._split_header_payload_signature_from_token( access_token) headers = TokenManager.load_decoded_content_as_json(header) if headers['alg'] != 'RS256': # As public key is used, algorithm has to be RS256 raise SecurityError('Invalid algorithm!', code=401) decoded_signature = TokenManager.b64decode(signature) pubkey = PublicKey.load_pkcs1_openssl_pem(public_key) message = header + '.' + encoded_payload verified = rsa.verify(message.encode('utf-8'), decoded_signature, pubkey) return verified, encoded_payload
def validate(self, access_token, *, scopes=None, scope_regex=None, public_key=None, online=False): if online: return JWTTokenManager.parse_validate_response( self._online_validate(access_token, scopes=scopes)), access_token else: if not public_key: raise SecurityError( 'Invalid public key: {}'.format(public_key)) return self._offline_validate(access_token, public_key, scopes=scopes, scope_regex=scope_regex)
def _validate_payload_expiry(json_payload): if float(json_payload['exp']) <= time.time(): raise SecurityError('Token expired!', code=401)
def get_scope_str(scopes): if not scopes or not isinstance(scopes, list): raise SecurityError('Invalid auth scope(s): {}'.format(scopes)) return ','.join(map(str, scopes))