blob: 9a35b762176a9d9b6185440006a93dcc823ed60b [file] [log] [blame]
ghanshyamf9ded352016-04-12 17:03:01 +09001# 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.
Ghanshyamd5394652018-04-26 07:59:32 +000015import base64
ghanshyamf9ded352016-04-12 17:03:01 +090016
17import jsonschema
18from oslo_utils import timeutils
Ghanshyamd5394652018-04-26 07:59:32 +000019import six
ghanshyamf9ded352016-04-12 17:03:01 +090020
21# JSON Schema validator and format checker used for JSON Schema validation
22JSONSCHEMA_VALIDATOR = jsonschema.Draft4Validator
23FORMAT_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')
34def _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
Ghanshyamd5394652018-04-26 07:59:32 +000042
43
44@jsonschema.FormatChecker.cls_checks('base64')
45def _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