ghanshyam | f9ded35 | 2016-04-12 17:03:01 +0900 | [diff] [blame] | 1 | # Copyright 2016 NEC 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. |
Ghanshyam | d539465 | 2018-04-26 07:59:32 +0000 | [diff] [blame] | 15 | import base64 |
ghanshyam | f9ded35 | 2016-04-12 17:03:01 +0900 | [diff] [blame] | 16 | |
| 17 | import jsonschema |
| 18 | from oslo_utils import timeutils |
Ghanshyam | d539465 | 2018-04-26 07:59:32 +0000 | [diff] [blame] | 19 | import six |
ghanshyam | f9ded35 | 2016-04-12 17:03:01 +0900 | [diff] [blame] | 20 | |
| 21 | # JSON Schema validator and format checker used for JSON Schema validation |
| 22 | JSONSCHEMA_VALIDATOR = jsonschema.Draft4Validator |
| 23 | FORMAT_CHECKER = jsonschema.draft4_format_checker |
| 24 | |
| 25 | |
| 26 | # NOTE(gmann): Add customized format checker for 'date-time' format because: |
| 27 | # 1. jsonschema needs strict_rfc3339 or isodate module to be installed |
| 28 | # for proper date-time checking as per rfc3339. |
| 29 | # 2. Nova or other OpenStack components handle the date time format as |
| 30 | # ISO 8601 which is defined in oslo_utils.timeutils |
| 31 | # so this checker will validate the date-time as defined in |
| 32 | # oslo_utils.timeutils |
| 33 | @FORMAT_CHECKER.checks('iso8601-date-time') |
| 34 | def _validate_datetime_format(instance): |
| 35 | try: |
| 36 | if isinstance(instance, jsonschema.compat.str_types): |
| 37 | timeutils.parse_isotime(instance) |
| 38 | except ValueError: |
| 39 | return False |
| 40 | else: |
| 41 | return True |
Ghanshyam | d539465 | 2018-04-26 07:59:32 +0000 | [diff] [blame] | 42 | |
| 43 | |
| 44 | @jsonschema.FormatChecker.cls_checks('base64') |
| 45 | def _validate_base64_format(instance): |
| 46 | try: |
| 47 | if isinstance(instance, six.text_type): |
| 48 | instance = instance.encode('utf-8') |
| 49 | base64.decodestring(instance) |
| 50 | except base64.binascii.Error: |
| 51 | return False |
| 52 | except TypeError: |
| 53 | # The name must be string type. If instance isn't string type, the |
| 54 | # TypeError will be raised at here. |
| 55 | return False |
| 56 | |
| 57 | return True |