def put(self, action_alias_ref_or_id, action_alias): action_alias_db = self._get_by_ref_or_id(ref_or_id=action_alias_ref_or_id) LOG.debug("PUT /actionalias/ lookup with id=%s found object: %s", action_alias_ref_or_id, action_alias_db) try: if action_alias.id is not None and action_alias.id is not "" and action_alias.id != action_alias_ref_or_id: LOG.warning( "Discarding mismatched id=%s found in payload and using uri_id=%s.", action_alias.id, action_alias_ref_or_id, ) old_action_alias_db = action_alias_db action_alias_db = ActionAliasAPI.to_model(action_alias) action_alias_db.id = action_alias_ref_or_id action_alias_db = ActionAlias.add_or_update(action_alias_db) except (ValidationError, ValueError) as e: LOG.exception("Validation failed for action alias data=%s", action_alias) pecan.abort(http_client.BAD_REQUEST, str(e)) return extra = {"old_action_alias_db": old_action_alias_db, "new_action_alias_db": action_alias_db} LOG.audit("Action alias updated. ActionAlias.id=%s." % (action_alias_db.id), extra=extra) action_alias_api = ActionAliasAPI.from_model(action_alias_db) return action_alias_api
def post(self, action_alias): """ Create a new ActionAlias. Handles requests: POST /actionalias/ """ try: action_alias_db = ActionAliasAPI.to_model(action_alias) LOG.debug( '/actionalias/ POST verified ActionAliasAPI and formulated ActionAliasDB=%s', action_alias_db) action_alias_db = ActionAlias.add_or_update(action_alias_db) except (ValidationError, ValueError, ValueValidationException) as e: LOG.exception('Validation failed for action alias data=%s.', action_alias) pecan.abort(http_client.BAD_REQUEST, str(e)) return extra = {'action_alias_db': action_alias_db} LOG.audit('Action alias created. ActionAlias.id=%s' % (action_alias_db.id), extra=extra) action_alias_api = ActionAliasAPI.from_model(action_alias_db) return action_alias_api
def put(self, action_alias_ref_or_id, action_alias): action_alias_db = self._get_by_ref_or_id( ref_or_id=action_alias_ref_or_id) LOG.debug('PUT /actionalias/ lookup with id=%s found object: %s', action_alias_ref_or_id, action_alias_db) try: if action_alias.id is not None and action_alias.id is not '' and \ action_alias.id != action_alias_ref_or_id: LOG.warning( 'Discarding mismatched id=%s found in payload and using uri_id=%s.', action_alias.id, action_alias_ref_or_id) old_action_alias_db = action_alias_db action_alias_db = ActionAliasAPI.to_model(action_alias) action_alias_db.id = action_alias_ref_or_id action_alias_db = ActionAlias.add_or_update(action_alias_db) except (ValidationError, ValueError) as e: LOG.exception('Validation failed for action alias data=%s', action_alias) pecan.abort(http_client.BAD_REQUEST, str(e)) return extra = { 'old_action_alias_db': old_action_alias_db, 'new_action_alias_db': action_alias_db } LOG.audit('Action alias updated. ActionAlias.id=%s.' % (action_alias_db.id), extra=extra) action_alias_api = ActionAliasAPI.from_model(action_alias_db) return action_alias_api
def _register_action_alias(self, pack, action_alias): content = self._meta_loader.load(action_alias) pack_field = content.get('pack', None) if not pack_field: content['pack'] = pack pack_field = pack if pack_field != pack: raise Exception('Model is in pack "%s" but field "pack" is different: %s' % (pack, pack_field)) action_alias_api = ActionAliasAPI(**content) action_alias_api.validate() action_alias_db = ActionAliasAPI.to_model(action_alias_api) try: action_alias_db.id = ActionAlias.get_by_name(action_alias_api.name).id except ValueError: LOG.info('ActionAlias %s not found. Creating new one.', action_alias) try: action_alias_db = ActionAlias.add_or_update(action_alias_db) extra = {'action_alias_db': action_alias_db} LOG.audit('Action alias updated. Action alias %s from %s.', action_alias_db, action_alias, extra=extra) except Exception: LOG.exception('Failed to create action alias %s.', action_alias_api.name) raise
def post(self, action_alias): """ Create a new ActionAlias. Handles requests: POST /actionalias/ """ try: action_alias_db = ActionAliasAPI.to_model(action_alias) LOG.debug('/actionalias/ POST verified ActionAliasAPI and formulated ActionAliasDB=%s', action_alias_db) action_alias_db = ActionAlias.add_or_update(action_alias_db) except (ValidationError, ValueError, ValueValidationException) as e: LOG.exception('Validation failed for action alias data=%s.', action_alias) pecan.abort(http_client.BAD_REQUEST, str(e)) return except StackStormDBObjectConflictError as e: LOG.warn('ActionAlias creation of %s failed with uniqueness conflict.', action_alias, exc_info=True) pecan.abort(http_client.CONFLICT, str(e), body={'conflict-id': e.conflict_id}) return extra = {'action_alias_db': action_alias_db} LOG.audit('Action alias created. ActionAlias.id=%s' % (action_alias_db.id), extra=extra) action_alias_api = ActionAliasAPI.from_model(action_alias_db) return action_alias_api
def post(self, action_alias, requester_user): """ Create a new ActionAlias. Handles requests: POST /actionalias/ """ permission_type = PermissionType.ACTION_ALIAS_CREATE rbac_utils = get_rbac_backend().get_utils_class() rbac_utils.assert_user_has_resource_api_permission(user_db=requester_user, resource_api=action_alias, permission_type=permission_type) try: action_alias_db = ActionAliasAPI.to_model(action_alias) LOG.debug('/actionalias/ POST verified ActionAliasAPI and formulated ActionAliasDB=%s', action_alias_db) action_alias_db = ActionAlias.add_or_update(action_alias_db) except (ValidationError, ValueError, ValueValidationException) as e: LOG.exception('Validation failed for action alias data=%s.', action_alias) abort(http_client.BAD_REQUEST, six.text_type(e)) return extra = {'action_alias_db': action_alias_db} LOG.audit('Action alias created. ActionAlias.id=%s' % (action_alias_db.id), extra=extra) action_alias_api = ActionAliasAPI.from_model(action_alias_db) return Response(json=action_alias_api, status=http_client.CREATED)
def _register_aliases(self, aliases=None): registered_count = 0 for alias in aliases: LOG.debug('Loading alias from %s.', alias) try: content = self._meta_loader.load(alias) action_alias_api = ActionAliasAPI(**content) action_alias_db = ActionAliasAPI.to_model(action_alias_api) try: action_alias_db.id = ActionAlias.get_by_name( action_alias_api.name).id except ValueError: LOG.info('ActionAlias %s not found. Creating new one.', alias) try: action_alias_db = ActionAlias.add_or_update( action_alias_db) extra = {'action_alias_db': action_alias_db} LOG.audit('Action alias updated. Action alias %s from %s.', action_alias_db, alias, extra=extra) except Exception: LOG.exception('Failed to create action alias %s.', action_alias_api.name) except Exception: LOG.exception('Failed registering alias from %s.', alias) else: registered_count += 1 return registered_count
def _get_action_alias_db(self, pack, action_alias, ignore_metadata_file_error=False): """ Retrieve ActionAliasDB object. :param ignore_metadata_file_error: True to ignore the error when we can't infer metadata_file attribute (e.g. inside tests). :type ignore_metadata_file_error: ``bool`` """ content = self._meta_loader.load(action_alias) pack_field = content.get('pack', None) if not pack_field: content['pack'] = pack pack_field = pack if pack_field != pack: raise Exception('Model is in pack "%s" but field "pack" is different: %s' % (pack, pack_field)) # Add in "metadata_file" attribute which stores path to the pack metadata file relative to # the pack directory try: metadata_file = content_utils.get_relative_path_to_pack_file(pack_ref=pack, file_path=action_alias, use_pack_cache=True) except ValueError as e: if not ignore_metadata_file_error: raise e else: content['metadata_file'] = metadata_file action_alias_api = ActionAliasAPI(**content) action_alias_api.validate() action_alias_db = ActionAliasAPI.to_model(action_alias_api) return action_alias_db
def _register_action_alias(self, pack, action_alias): content = self._meta_loader.load(action_alias) pack_field = content.get('pack', None) if not pack_field: content['pack'] = pack pack_field = pack if pack_field != pack: raise Exception( 'Model is in pack "%s" but field "pack" is different: %s' % (pack, pack_field)) action_alias_api = ActionAliasAPI(**content) action_alias_api.validate() action_alias_db = ActionAliasAPI.to_model(action_alias_api) try: action_alias_db.id = ActionAlias.get_by_name( action_alias_api.name).id except ValueError: LOG.info('ActionAlias %s not found. Creating new one.', action_alias) try: action_alias_db = ActionAlias.add_or_update(action_alias_db) extra = {'action_alias_db': action_alias_db} LOG.audit('Action alias updated. Action alias %s from %s.', action_alias_db, action_alias, extra=extra) except Exception: LOG.exception('Failed to create action alias %s.', action_alias_api.name) raise
def test_post_dup_name(self): post_resp = self._do_post(vars(ActionAliasAPI.from_model(self.alias3))) self.assertEqual(post_resp.status_int, 201) post_resp_dup_name = self._do_post(vars(ActionAliasAPI.from_model(self.alias3_generic))) self.assertEqual(post_resp_dup_name.status_int, 201) self.__do_delete(post_resp.json['id']) self.__do_delete(post_resp_dup_name.json['id'])
def put(self, action_alias, ref_or_id, requester_user): """ Update an action alias. Handles requests: PUT /actionalias/1 """ action_alias_db = self._get_by_ref_or_id(ref_or_id=ref_or_id) LOG.debug( "PUT /actionalias/ lookup with id=%s found object: %s", ref_or_id, action_alias_db, ) permission_type = PermissionType.ACTION_ALIAS_MODIFY rbac_utils = get_rbac_backend().get_utils_class() rbac_utils.assert_user_has_resource_db_permission( user_db=requester_user, resource_db=action_alias_db, permission_type=permission_type, ) if not hasattr(action_alias, "id"): action_alias.id = None try: if ( action_alias.id is not None and action_alias.id != "" and action_alias.id != ref_or_id ): LOG.warning( "Discarding mismatched id=%s found in payload and using uri_id=%s.", action_alias.id, ref_or_id, ) old_action_alias_db = action_alias_db action_alias_db = ActionAliasAPI.to_model(action_alias) action_alias_db.id = ref_or_id action_alias_db = ActionAlias.add_or_update(action_alias_db) except (ValidationError, ValueError) as e: LOG.exception("Validation failed for action alias data=%s", action_alias) abort(http_client.BAD_REQUEST, six.text_type(e)) return extra = { "old_action_alias_db": old_action_alias_db, "new_action_alias_db": action_alias_db, } LOG.audit( "Action alias updated. ActionAlias.id=%s." % (action_alias_db.id), extra=extra, ) action_alias_api = ActionAliasAPI.from_model(action_alias_db) return action_alias_api
def test_update_existing_alias(self): post_resp = self._do_post(vars(ActionAliasAPI.from_model(self.alias3))) self.assertEqual(post_resp.status_int, 201) self.assertEqual(post_resp.json['name'], self.alias3['name']) data = vars(ActionAliasAPI.from_model(self.alias3)) data['name'] = 'updated-alias-name' put_resp = self.app.put_json('/v1/actionalias/%s' % post_resp.json['id'], data) self.assertEqual(put_resp.json['name'], data['name']) get_resp = self.app.get('/v1/actionalias/%s' % post_resp.json['id']) self.assertEqual(get_resp.json['name'], data['name']) del_resp = self.__do_delete(post_resp.json['id']) self.assertEqual(del_resp.status_int, 204)
def _register_aliases(self, aliases=None): registered_count = 0 for alias in aliases: LOG.debug('Loading alias from %s.', alias) try: content = self._meta_loader.load(alias) action_alias_api = ActionAliasAPI(**content) action_alias_db = ActionAliasAPI.to_model(action_alias_api) try: action_alias_db.id = ActionAlias.get_by_name(action_alias_api.name).id except ValueError: LOG.info('ActionAlias %s not found. Creating new one.', alias) try: action_alias_db = ActionAlias.add_or_update(action_alias_db) extra = {'action_alias_db': action_alias_db} LOG.audit('Action alias updated. Action alias %s from %s.', action_alias_db, alias, extra=extra) except Exception: LOG.exception('Failed to create action alias %s.', action_alias_api.name) except Exception: LOG.exception('Failed registering alias from %s.', alias) else: registered_count += 1 return registered_count
def match(self, action_alias_match_api, **kwargs): """ Run a chatops command Handles requests: POST /actionalias/match """ command = action_alias_match_api.command try: # 1. Get aliases aliases_resp = super(ActionAliasController, self)._get_all(**kwargs) aliases = [ActionAliasAPI(**alias) for alias in aliases_resp.json] # 2. Match alias(es) to command matches = match_command_to_alias(command, aliases) if len(matches) > 1: raise ActionAliasAmbiguityException( "Command '%s' matched more than 1 pattern" % command, matches=matches, command=command) elif len(matches) == 0: raise ActionAliasAmbiguityException( "Command '%s' matched no patterns" % command, matches=[], command=command) return [self._match_tuple_to_dict(match) for match in matches] except ActionAliasAmbiguityException as e: LOG.exception('Command "%s" matched (%s) patterns.', e.command, len(e.matches)) return abort(http_client.BAD_REQUEST, str(e))
def test_update_existing_alias(self): post_resp = self._do_post(vars(ActionAliasAPI.from_model(self.alias3))) self.assertEqual(post_resp.status_int, 201) self.assertEqual(post_resp.json["name"], self.alias3["name"]) data = vars(ActionAliasAPI.from_model(self.alias3)) data["name"] = "updated-alias-name" put_resp = self.app.put_json("/v1/actionalias/%s" % post_resp.json["id"], data) self.assertEqual(put_resp.json["name"], data["name"]) get_resp = self.app.get("/v1/actionalias/%s" % post_resp.json["id"]) self.assertEqual(get_resp.json["name"], data["name"]) del_resp = self.__do_delete(post_resp.json["id"]) self.assertEqual(del_resp.status_int, 204)
def _get_action_alias_db(self, pack, action_alias): """ Retrieve ActionAliasDB object. """ content = self._meta_loader.load(action_alias) pack_field = content.get("pack", None) if not pack_field: content["pack"] = pack pack_field = pack if pack_field != pack: raise Exception('Model is in pack "%s" but field "pack" is different: %s' % (pack, pack_field)) action_alias_api = ActionAliasAPI(**content) action_alias_api.validate() action_alias_db = ActionAliasAPI.to_model(action_alias_api) return action_alias_db
def put(self, action_alias, ref_or_id, requester_user): """ Update an action alias. Handles requests: PUT /actionalias/1 """ action_alias_db = self._get_by_ref_or_id(ref_or_id=ref_or_id) LOG.debug('PUT /actionalias/ lookup with id=%s found object: %s', ref_or_id, action_alias_db) permission_type = PermissionType.ACTION_ALIAS_MODIFY rbac_utils.assert_user_has_resource_db_permission( user_db=requester_user, resource_db=action_alias_db, permission_type=permission_type) if not hasattr(action_alias, 'id'): action_alias.id = None try: if action_alias.id is not None and action_alias.id is not '' and \ action_alias.id != ref_or_id: LOG.warning( 'Discarding mismatched id=%s found in payload and using uri_id=%s.', action_alias.id, ref_or_id) old_action_alias_db = action_alias_db action_alias_db = ActionAliasAPI.to_model(action_alias) action_alias_db.id = ref_or_id action_alias_db = ActionAlias.add_or_update(action_alias_db) except (ValidationError, ValueError) as e: LOG.exception('Validation failed for action alias data=%s', action_alias) abort(http_client.BAD_REQUEST, str(e)) return extra = { 'old_action_alias_db': old_action_alias_db, 'new_action_alias_db': action_alias_db } LOG.audit('Action alias updated. ActionAlias.id=%s.' % (action_alias_db.id), extra=extra) action_alias_api = ActionAliasAPI.from_model(action_alias_db) return action_alias_api
def post(self, payload): action_alias_name = payload.name if payload else None if not action_alias_name: pecan.abort(http_client.BAD_REQUEST, 'Alias execution "name" is required') format_str = payload.format or '' command = payload.command or '' try: action_alias_db = ActionAlias.get_by_name(action_alias_name) except ValueError: action_alias_db = None if not action_alias_db: msg = 'Unable to identify action alias with name "%s".' % (action_alias_name) pecan.abort(http_client.NOT_FOUND, msg) return if not action_alias_db.enabled: msg = 'Action alias with name "%s" is disabled.' % (action_alias_name) pecan.abort(http_client.BAD_REQUEST, msg) return execution_parameters = extract_parameters_for_action_alias_db( action_alias_db=action_alias_db, format_str=format_str, param_stream=command) notify = self._get_notify_field(payload) context = { 'action_alias_ref': reference.get_ref_from_model(action_alias_db), 'api_user': payload.user, 'user': get_requester(), 'source_channel': payload.source_channel } execution = self._schedule_execution(action_alias_db=action_alias_db, params=execution_parameters, notify=notify, context=context) result = { 'execution': execution, 'actionalias': ActionAliasAPI.from_model(action_alias_db) } if action_alias_db.ack: if 'format' in action_alias_db.ack: result.update({ 'message': render({'alias': action_alias_db.ack['format']}, result)['alias'] }) if 'extra' in action_alias_db.ack: result.update({ 'extra': render(action_alias_db.ack['extra'], result) }) return result
def post(self, payload): action_alias_name = payload.name if payload else None if not action_alias_name: pecan.abort(http_client.BAD_REQUEST, 'Alias execution "name" is required') format_str = payload.format or '' command = payload.command or '' try: action_alias_db = ActionAlias.get_by_name(action_alias_name) except ValueError: action_alias_db = None if not action_alias_db: msg = 'Unable to identify action alias with name "%s".' % ( action_alias_name) pecan.abort(http_client.NOT_FOUND, msg) return if not action_alias_db.enabled: msg = 'Action alias with name "%s" is disabled.' % ( action_alias_name) pecan.abort(http_client.BAD_REQUEST, msg) return execution_parameters = self._extract_parameters( action_alias_db=action_alias_db, format_str=format_str, param_stream=command) notify = self._get_notify_field(payload) context = { 'action_alias_ref': reference.get_ref_from_model(action_alias_db), 'api_user': payload.user, 'user': get_requester(), 'source_channel': payload.source_channel } execution = self._schedule_execution(action_alias_db=action_alias_db, params=execution_parameters, notify=notify, context=context) result = { 'execution': execution, 'actionalias': ActionAliasAPI.from_model(action_alias_db) } if action_alias_db.ack and 'format' in action_alias_db.ack: result.update({ 'message': render({'alias': action_alias_db.ack['format']}, result)['alias'] }) return result
def _get_action_alias_db(self, pack, action_alias): """ Retrieve ActionAliasDB object. """ content = self._meta_loader.load(action_alias) pack_field = content.get('pack', None) if not pack_field: content['pack'] = pack pack_field = pack if pack_field != pack: raise Exception( 'Model is in pack "%s" but field "pack" is different: %s' % (pack, pack_field)) action_alias_api = ActionAliasAPI(**content) action_alias_api.validate() action_alias_db = ActionAliasAPI.to_model(action_alias_api) return action_alias_db
def post(self, action_alias): """ Create a new ActionAlias. Handles requests: POST /actionalias/ """ try: action_alias_db = ActionAliasAPI.to_model(action_alias) LOG.debug("/actionalias/ POST verified ActionAliasAPI and formulated ActionAliasDB=%s", action_alias_db) action_alias_db = ActionAlias.add_or_update(action_alias_db) except (ValidationError, ValueError, ValueValidationException) as e: LOG.exception("Validation failed for action alias data=%s.", action_alias) pecan.abort(http_client.BAD_REQUEST, str(e)) return extra = {"action_alias_db": action_alias_db} LOG.audit("Action alias created. ActionAlias.id=%s" % (action_alias_db.id), extra=extra) action_alias_api = ActionAliasAPI.from_model(action_alias_db) return action_alias_api
def _get_action_alias_db(self, pack, action_alias, ignore_metadata_file_error=False): """ Retrieve ActionAliasDB object. :param ignore_metadata_file_error: True to ignore the error when we can't infer metadata_file attribute (e.g. inside tests). :type ignore_metadata_file_error: ``bool`` """ content = self._meta_loader.load(action_alias) pack_field = content.get("pack", None) if not pack_field: content["pack"] = pack pack_field = pack if pack_field != pack: raise Exception( 'Model is in pack "%s" but field "pack" is different: %s' % (pack, pack_field)) # Add in "metadata_file" attribute which stores path to the pack metadata file relative to # the pack directory try: metadata_file = content_utils.get_relative_path_to_pack_file( pack_ref=pack, file_path=action_alias, use_pack_cache=True) except ValueError as e: if not ignore_metadata_file_error: raise e else: content["metadata_file"] = metadata_file # Pass override information altered = self._override_loader.override(pack, "aliases", content) action_alias_api = ActionAliasAPI(**content) action_alias_api.validate() action_alias_db = ActionAliasAPI.to_model(action_alias_api) return action_alias_db, altered
def test_post_delete(self): post_resp = self._do_post(vars(ActionAliasAPI.from_model(self.alias3))) self.assertEqual(post_resp.status_int, 201) get_resp = self.app.get("/v1/actionalias/%s" % post_resp.json["id"]) self.assertEqual(get_resp.status_int, 200) self.assertEqual(get_resp.json["name"], self.alias3.name, "Incorrect aliases retrieved.") del_resp = self.__do_delete(post_resp.json["id"]) self.assertEqual(del_resp.status_int, 204) get_resp = self.app.get("/v1/actionalias/%s" % post_resp.json["id"], expect_errors=True) self.assertEqual(get_resp.status_int, 404)
def put(self, action_alias, ref_or_id, requester_user): """ Update an action alias. Handles requests: PUT /actionalias/1 """ action_alias_db = self._get_by_ref_or_id(ref_or_id=ref_or_id) LOG.debug('PUT /actionalias/ lookup with id=%s found object: %s', ref_or_id, action_alias_db) permission_type = PermissionType.ACTION_ALIAS_MODIFY rbac_utils = get_rbac_backend().get_utils_class() rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user, resource_db=action_alias_db, permission_type=permission_type) if not hasattr(action_alias, 'id'): action_alias.id = None try: if action_alias.id is not None and action_alias.id != '' and \ action_alias.id != ref_or_id: LOG.warning('Discarding mismatched id=%s found in payload and using uri_id=%s.', action_alias.id, ref_or_id) old_action_alias_db = action_alias_db action_alias_db = ActionAliasAPI.to_model(action_alias) action_alias_db.id = ref_or_id action_alias_db = ActionAlias.add_or_update(action_alias_db) except (ValidationError, ValueError) as e: LOG.exception('Validation failed for action alias data=%s', action_alias) abort(http_client.BAD_REQUEST, six.text_type(e)) return extra = {'old_action_alias_db': old_action_alias_db, 'new_action_alias_db': action_alias_db} LOG.audit('Action alias updated. ActionAlias.id=%s.' % (action_alias_db.id), extra=extra) action_alias_api = ActionAliasAPI.from_model(action_alias_db) return action_alias_api
def help(self, filter, pack, limit, offset, **kwargs): """ Get available help strings for action aliases. Handles requests: GET /actionalias/help """ try: aliases_resp = super(ActionAliasController, self)._get_all(**kwargs) aliases = [ActionAliasAPI(**alias) for alias in aliases_resp.json] return generate_helpstring_result(aliases, filter, pack, int(limit), int(offset)) except (TypeError) as e: LOG.exception('Helpstring request contains an invalid data type: %s.', six.text_type(e)) return abort(http_client.BAD_REQUEST, six.text_type(e))
def test_post_delete(self): post_resp = self._do_post(vars(ActionAliasAPI.from_model(self.alias3))) self.assertEqual(post_resp.status_int, 201) get_resp = self.app.get('/exp/actionalias/%s' % post_resp.json['name']) self.assertEqual(get_resp.status_int, 200) self.assertEqual(get_resp.json['name'], self.alias3.name, 'Incorrect aliases retrieved.') del_resp = self.__do_delete(post_resp.json['id']) self.assertEqual(del_resp.status_int, 204) get_resp = self.app.get('/exp/actionalias/%s' % post_resp.json['name'], expect_errors=True) self.assertEqual(get_resp.status_int, 404)
def test_post_delete(self): post_resp = self._do_post(vars(ActionAliasAPI.from_model(self.alias3))) self.assertEqual(post_resp.status_int, 201) get_resp = self.app.get('/v1/actionalias/%s' % post_resp.json['id']) self.assertEqual(get_resp.status_int, 200) self.assertEqual(get_resp.json['name'], self.alias3.name, 'Incorrect aliases retrieved.') del_resp = self.__do_delete(post_resp.json['id']) self.assertEqual(del_resp.status_int, 204) get_resp = self.app.get('/v1/actionalias/%s' % post_resp.json['id'], expect_errors=True) self.assertEqual(get_resp.status_int, 404)
def match(self, action_alias_match_api): """ Find a matching action alias. Handles requests: POST /actionalias/match """ command = action_alias_match_api.command try: match = get_matching_alias(command=command) except ActionAliasAmbiguityException as e: LOG.exception('Command "%s" matched (%s) patterns.', e.command, len(e.matches)) return abort(http_client.BAD_REQUEST, str(e)) # Convert ActionAliasDB to API action_alias_api = ActionAliasAPI.from_model(match[0]) match = [action_alias_api, match[1], match[2]] result = self._match_tuple_to_dict(match=match) return result
def match(self, action_alias_match_api): """ Find a matching action alias. Handles requests: POST /actionalias/match """ command = action_alias_match_api.command try: format_ = get_matching_alias(command=command) except ActionAliasAmbiguityException as e: LOG.exception('Command "%s" matched (%s) patterns.', e.command, len(e.matches)) return abort(http_client.BAD_REQUEST, six.text_type(e)) # Convert ActionAliasDB to API action_alias_api = ActionAliasAPI.from_model(format_['alias']) return { 'actionalias': action_alias_api, 'display': format_['display'], 'representation': format_['representation'], }
def _post(self, payload, requester_user, show_secrets=False, match_multiple=False): action_alias_name = payload.name if payload else None if not action_alias_name: abort(http_client.BAD_REQUEST, 'Alias execution "name" is required') return if not requester_user: requester_user = UserDB(cfg.CONF.system_user.user) format_str = payload.format or '' command = payload.command or '' try: action_alias_db = ActionAlias.get_by_name(action_alias_name) except ValueError: action_alias_db = None if not action_alias_db: msg = 'Unable to identify action alias with name "%s".' % (action_alias_name) abort(http_client.NOT_FOUND, msg) return if not action_alias_db.enabled: msg = 'Action alias with name "%s" is disabled.' % (action_alias_name) abort(http_client.BAD_REQUEST, msg) return if match_multiple: multiple_execution_parameters = extract_parameters_for_action_alias_db( action_alias_db=action_alias_db, format_str=format_str, param_stream=command, match_multiple=match_multiple) else: multiple_execution_parameters = [ extract_parameters_for_action_alias_db( action_alias_db=action_alias_db, format_str=format_str, param_stream=command, match_multiple=match_multiple) ] notify = self._get_notify_field(payload) context = { 'action_alias_ref': reference.get_ref_from_model(action_alias_db), 'api_user': payload.user, 'user': requester_user.name, 'source_channel': payload.source_channel } results = [] for execution_parameters in multiple_execution_parameters: execution = self._schedule_execution(action_alias_db=action_alias_db, params=execution_parameters, notify=notify, context=context, show_secrets=show_secrets, requester_user=requester_user) result = { 'execution': execution, 'actionalias': ActionAliasAPI.from_model(action_alias_db) } if action_alias_db.ack: try: if 'format' in action_alias_db.ack: message = render({'alias': action_alias_db.ack['format']}, result)['alias'] result.update({ 'message': message }) except UndefinedError as e: result.update({ 'message': ('Cannot render "format" in field "ack" for alias. ' + six.text_type(e)) }) try: if 'extra' in action_alias_db.ack: result.update({ 'extra': render(action_alias_db.ack['extra'], result) }) except UndefinedError as e: result.update({ 'extra': ('Cannot render "extra" in field "ack" for alias. ' + six.text_type(e)) }) results.append(result) return results
def test_user_has_resource_api_permission(self): resolver = ActionAliasPermissionsResolver() # Admin user, should always return true user_db = self.users['admin'] resource_db = self.resources['alias_1'] resource_api = ActionAliasAPI.from_model(resource_db) self.assertUserHasResourceApiPermission( resolver=resolver, user_db=user_db, resource_api=resource_api, permission_type=PermissionType.ACTION_ALIAS_CREATE) # Observer, should return false user_db = self.users['observer'] resource_db = self.resources['alias_1'] resource_api = ActionAliasAPI.from_model(resource_db) self.assertUserDoesntHaveResourceApiPermission( resolver=resolver, user_db=user_db, resource_api=resource_api, permission_type=PermissionType.ACTION_ALIAS_CREATE) # No roles, should return false user_db = self.users['no_roles'] resource_db = self.resources['alias_1'] resource_api = ActionAliasAPI.from_model(resource_db) self.assertUserDoesntHaveResourceApiPermission( resolver=resolver, user_db=user_db, resource_api=resource_api, permission_type=PermissionType.ACTION_ALIAS_CREATE) # Custom role with no permission grants, should return false user_db = self.users['1_custom_role_no_permissions'] resource_db = self.resources['alias_1'] resource_api = ActionAliasAPI.from_model(resource_db) self.assertUserDoesntHaveResourceApiPermission( resolver=resolver, user_db=user_db, resource_api=resource_api, permission_type=PermissionType.ACTION_ALIAS_CREATE) # Custom role with "action_alias_create" grant on parent pack user_db = self.users['alias_pack_alias_create_grant'] resource_db = self.resources['alias_1'] resource_api = ActionAliasAPI.from_model(resource_db) self.assertUserHasResourceApiPermission( resolver=resolver, user_db=user_db, resource_api=resource_api, permission_type=PermissionType.ACTION_ALIAS_CREATE) # Custom role with "action_alias_all" grant on the parent pack user_db = self.users['alias_pack_alias_all_grant'] resource_db = self.resources['alias_1'] resource_api = ActionAliasAPI.from_model(resource_db) self.assertUserHasResourceApiPermission( resolver=resolver, user_db=user_db, resource_api=resource_api, permission_type=PermissionType.ACTION_ALIAS_CREATE) # Custom role with "action_alias_create" grant directly on the resource user_db = self.users['alias_alias_create_grant'] resource_db = self.resources['alias_1'] resource_api = ActionAliasAPI.from_model(resource_db) self.assertUserHasResourceApiPermission( resolver=resolver, user_db=user_db, resource_api=resource_api, permission_type=PermissionType.ACTION_ALIAS_CREATE) # Custom role with "action_alias_all" grant directly on the resource user_db = self.users['alias_all_grant'] resource_db = self.resources['alias_1'] resource_api = ActionAliasAPI.from_model(resource_db) self.assertUserHasResourceApiPermission( resolver=resolver, user_db=user_db, resource_api=resource_api, permission_type=PermissionType.ACTION_ALIAS_CREATE)
def _post(self, payload, requester_user, show_secrets=False, match_multiple=False): action_alias_name = payload.name if payload else None if not action_alias_name: abort(http_client.BAD_REQUEST, 'Alias execution "name" is required') return if not requester_user: requester_user = UserDB(cfg.CONF.system_user.user) format_str = payload.format or '' command = payload.command or '' try: action_alias_db = ActionAlias.get_by_name(action_alias_name) except ValueError: action_alias_db = None if not action_alias_db: msg = 'Unable to identify action alias with name "%s".' % ( action_alias_name) abort(http_client.NOT_FOUND, msg) return if not action_alias_db.enabled: msg = 'Action alias with name "%s" is disabled.' % ( action_alias_name) abort(http_client.BAD_REQUEST, msg) return if match_multiple: multiple_execution_parameters = extract_parameters_for_action_alias_db( action_alias_db=action_alias_db, format_str=format_str, param_stream=command, match_multiple=match_multiple) else: multiple_execution_parameters = [ extract_parameters_for_action_alias_db( action_alias_db=action_alias_db, format_str=format_str, param_stream=command, match_multiple=match_multiple) ] notify = self._get_notify_field(payload) context = { 'action_alias_ref': reference.get_ref_from_model(action_alias_db), 'api_user': payload.user, 'user': requester_user.name, 'source_channel': payload.source_channel, } inject_immutable_parameters( action_alias_db=action_alias_db, multiple_execution_parameters=multiple_execution_parameters, action_context=context) results = [] for execution_parameters in multiple_execution_parameters: execution = self._schedule_execution( action_alias_db=action_alias_db, params=execution_parameters, notify=notify, context=context, show_secrets=show_secrets, requester_user=requester_user) result = { 'execution': execution, 'actionalias': ActionAliasAPI.from_model(action_alias_db) } if action_alias_db.ack: try: if 'format' in action_alias_db.ack: message = render( {'alias': action_alias_db.ack['format']}, result)['alias'] result.update({'message': message}) except UndefinedError as e: result.update({ 'message': ('Cannot render "format" in field "ack" for alias. ' + six.text_type(e)) }) try: if 'extra' in action_alias_db.ack: result.update({ 'extra': render(action_alias_db.ack['extra'], result) }) except UndefinedError as e: result.update({ 'extra': ('Cannot render "extra" in field "ack" for alias. ' + six.text_type(e)) }) results.append(result) return results
def post(self, payload, requester_user=None, show_secrets=False): action_alias_name = payload.name if payload else None if not action_alias_name: abort(http_client.BAD_REQUEST, 'Alias execution "name" is required') return if not requester_user: requester_user = UserDB(cfg.CONF.system_user.user) format_str = payload.format or '' command = payload.command or '' try: action_alias_db = ActionAlias.get_by_name(action_alias_name) except ValueError: action_alias_db = None if not action_alias_db: msg = 'Unable to identify action alias with name "%s".' % ( action_alias_name) abort(http_client.NOT_FOUND, msg) return if not action_alias_db.enabled: msg = 'Action alias with name "%s" is disabled.' % ( action_alias_name) abort(http_client.BAD_REQUEST, msg) return execution_parameters = extract_parameters_for_action_alias_db( action_alias_db=action_alias_db, format_str=format_str, param_stream=command) notify = self._get_notify_field(payload) context = { 'action_alias_ref': reference.get_ref_from_model(action_alias_db), 'api_user': payload.user, 'user': requester_user.name, 'source_channel': payload.source_channel } execution = self._schedule_execution(action_alias_db=action_alias_db, params=execution_parameters, notify=notify, context=context, show_secrets=show_secrets, requester_user=requester_user) result = { 'execution': execution, 'actionalias': ActionAliasAPI.from_model(action_alias_db) } if action_alias_db.ack: try: if 'format' in action_alias_db.ack: result.update({ 'message': render({'alias': action_alias_db.ack['format']}, result)['alias'] }) except UndefinedError as e: result.update({ 'message': 'Cannot render "format" in field "ack" for alias. ' + e.message }) try: if 'extra' in action_alias_db.ack: result.update({ 'extra': render(action_alias_db.ack['extra'], result) }) except UndefinedError as e: result.update({ 'extra': 'Cannot render "extra" in field "ack" for alias. ' + e.message }) return Response(json=result, status=http_client.CREATED)