Rick Bartra | ed95005 | 2017-06-29 17:20:33 -0400 | [diff] [blame] | 1 | # Copyright 2017 AT&T Corporation. |
| 2 | # All Rights Reserved. |
| 3 | # |
| 4 | # Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 5 | # not use this file except in compliance with the License. You may obtain |
| 6 | # a copy of the License at |
| 7 | # |
| 8 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | # |
| 10 | # Unless required by applicable law or agreed to in writing, software |
| 11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 13 | # License for the specific language governing permissions and limitations |
| 14 | # under the License. |
| 15 | import yaml |
| 16 | |
| 17 | from oslo_log import log as logging |
| 18 | |
| 19 | from tempest.lib import exceptions |
| 20 | |
| 21 | from patrole_tempest_plugin.rbac_utils import RbacAuthority |
| 22 | |
| 23 | LOG = logging.getLogger(__name__) |
| 24 | |
| 25 | |
| 26 | class RequirementsParser(object): |
| 27 | _inner = None |
| 28 | |
| 29 | class Inner(object): |
| 30 | _rbac_map = None |
| 31 | |
| 32 | def __init__(self, filepath): |
| 33 | with open(filepath) as f: |
| 34 | RequirementsParser.Inner._rbac_map = \ |
| 35 | list(yaml.safe_load_all(f)) |
| 36 | |
| 37 | def __init__(self, filepath): |
| 38 | if RequirementsParser._inner is None: |
| 39 | RequirementsParser._inner = RequirementsParser.Inner(filepath) |
| 40 | |
| 41 | @staticmethod |
| 42 | def parse(component): |
| 43 | try: |
| 44 | for section in RequirementsParser.Inner._rbac_map: |
| 45 | if component in section: |
| 46 | return section[component] |
| 47 | except yaml.parser.ParserError: |
| 48 | LOG.error("Error while parsing the requirements YAML file. Did " |
| 49 | "you pass a valid component name from the test case?") |
| 50 | return None |
| 51 | |
| 52 | |
| 53 | class RequirementsAuthority(RbacAuthority): |
| 54 | def __init__(self, filepath=None, component=None): |
| 55 | if filepath is not None and component is not None: |
| 56 | self.roles_dict = RequirementsParser(filepath).parse(component) |
| 57 | else: |
| 58 | self.roles_dict = None |
| 59 | |
| 60 | def allowed(self, rule_name, role): |
| 61 | if self.roles_dict is None: |
| 62 | raise exceptions.InvalidConfiguration( |
| 63 | "Roles dictionary parsed from requirements YAML file is " |
| 64 | "empty. Ensure the requirements YAML file is correctly " |
| 65 | "formatted.") |
| 66 | try: |
| 67 | _api = self.roles_dict[rule_name] |
| 68 | return role in _api |
| 69 | except KeyError: |
| 70 | raise KeyError("'%s' API is not defined in the requirements YAML " |
| 71 | "file" % rule_name) |
| 72 | return False |