Debian Codegraph @

neutron_lib/api/validators/__init__.py

raw
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13 import collections
14 import functools
15 import inspect
16 import re
17
18 import netaddr
19 from os_ken.lib.packet import ether_types
20 from oslo_config import cfg
21 from oslo_log import log as logging
22 from oslo_utils import netutils
23 from oslo_utils import strutils
24 from oslo_utils import uuidutils
25 from webob import exc
26
27 from neutron_lib._i18n import _
28 from neutron_lib import constants
29 from neutron_lib import exceptions as n_exc
30 from neutron_lib.plugins import directory
31
32
33 LOG = logging.getLogger(__name__)
34
35 # Used by range check to indicate no limit for a bound.
36 UNLIMITED = None
37
38 # Note: In order to ensure that the MAC address is unicast the first byte
39 # must be even.
40 _HEX_ELEM = constants.HEX_ELEM
41 MAC_PATTERN = f"^{_HEX_ELEM}[aceACE02468](:{_HEX_ELEM}{{2}}){{5}}$"
42
43
44 def _verify_dict_keys(expected_keys, target_dict, strict=True):
45 """Verify expected keys in a dictionary.
46
47 :param expected_keys: A list of keys expected to be present.
48 :param target_dict: The dictionary which should be verified.
49 :param strict: Specifies whether additional keys are allowed to be present.
50 :returns: None if the expected keys are found. Otherwise a human readable
51 message indicating why the validation failed.
52 """
53 if not isinstance(target_dict, dict):
54 msg_data = {'target_dict': target_dict,
55 'expected_keys': expected_keys}
56 msg = ("Invalid input. '%(target_dict)s' must be a dictionary "
57 "with keys: %(expected_keys)s")
58 LOG.debug(msg, msg_data)
59 return _(msg) % msg_data
60
61 expected_keys = set(expected_keys)
62 provided_keys = set(target_dict.keys())
63
64 predicate = expected_keys.__eq__ if strict else expected_keys.issubset
65
66 if not predicate(provided_keys):
67 msg_data = {'expected_keys': expected_keys,
68 'provided_keys': provided_keys}
69 msg = ("Validation of dictionary's keys failed. "
70 "Expected keys: %(expected_keys)s "
71 "Provided keys: %(provided_keys)s")
72 LOG.debug(msg, msg_data)
73 return _(msg) % msg_data
74
75
76 def _collect_duplicates(data_list):
77 """Collects duplicate items from a list and returns them.
78
79 :param data_list: A list of items to check for duplicates. The list may
80 include dict items.
81 :returns: A list of items that are duplicates in data_list. If no
82 duplicates are found, the returned list is empty.
83 """
84 seen = []
85 dups = []
86 for datum in data_list:
87 if datum in seen and datum not in dups:
88 dups.append(datum)
89 continue
90 seen.append(datum)
91 return dups
92
93
94 def is_attr_set(attribute):
95 """Determine if an attribute value is set.
96
97 :param attribute: The attribute value to check.
98 :returns: False if the attribute value is None or ATTR_NOT_SPECIFIED,
99 otherwise True.
100 """
101 return not (attribute is None or
102 attribute is constants.ATTR_NOT_SPECIFIED)
103
104
105 def _validate_list_of_items(item_validator, data, *args, **kwargs):
106 if not isinstance(data, list):
107 msg = _("'%s' is not a list") % data
108 return msg
109
110 dups = _collect_duplicates(data)
111
112 if dups:
113 msg = _("Duplicate items in the list: '%s'") % ', '.join(
114 [str(d) for d in dups])
115 return msg
116
117 for item in data:
118 msg = item_validator(item, *args, **kwargs)
119 if msg:
120 return msg
121
122
123 def _validate_list_of_items_non_empty(item_validator, data, *args, **kwargs):
124 res = _validate_list_of_items(item_validator, data, *args, **kwargs)
125
126 if res is not None:
127 return res
128
129 if len(data) == 0:
130 msg = _("List should not be empty")
131 return msg
132
133
134 def validate_values(data, valid_values=None, valid_values_display=None):
135 """Validate that the provided 'data' is within 'valid_values'.
136
137 :param data: The data to check within valid_values.
138 :param valid_values: A collection of values that 'data' must be in to be
139 valid. The collection can be any type that supports the 'in' operation.
140 :param valid_values_display: A string to display that describes the valid
141 values. This string is only displayed when an invalid value is
142 encountered.
143 If no string is provided, the string "valid_values" will be used.
144 :returns: The message to return if data not in valid_values.
145 :raises: TypeError if the values for 'data' or 'valid_values' are not
146 compatible for comparison or doesn't have __contains__.
147 If TypeError is raised this is considered a programming error and the
148 inputs (data) and (valid_values) must be checked so this is never
149 raised on validation.
150 """
151
152 # If valid_values is not specified we don't check against it.
153 if valid_values is None:
154 return
155
156 # Check if we can use 'in' to find membership of data in valid_values
157 contains = getattr(valid_values, "__contains__", None)
158 if callable(contains):
159 try:
160 if data not in valid_values:
161 valid_values_display = valid_values_display or 'valid_values'
162 msg_data = {'data': data,
163 'valid_values': valid_values_display}
164 msg = "%(data)s is not in %(valid_values)s"
165 LOG.debug(msg, msg_data)
166 return _(msg) % msg_data
167 except TypeError as e:
168 # This is a programming error
169 msg = (_("'data' of type '%(typedata)s' and 'valid_values' "
170 "of type '%(typevalues)s' are not "
171 "compatible for comparison") %
172 {'typedata': type(data),
173 'typevalues': type(valid_values)})
174 raise TypeError(msg) from e
175 else:
176 # This is a programming error
177 msg = (_("'valid_values' does not support membership operations"))
178 raise TypeError(msg)
179
180
181 def validate_not_empty_string_or_none(data, max_len=None):
182 """Validate data is a non-empty string or None.
183
184 :param data: The data to validate.
185 :param max_len: An optional cap on the str length to validate.
186 :returns: None if the data string is not None and is not an empty string,
187 otherwise a human readable message as to why the string data is
188 invalid.
189 """
190 if data is not None:
191 return validate_not_empty_string(data, max_len=max_len)
192
193
194 def validate_not_empty_string(data, max_len=None):
195 """Validate data is a non-empty/non-blank string.
196
197 :param data: The data to validate.
198 :param max_len: An optional cap on the length of the string data.
199 :returns: None if the data is non-empty/non-blank, otherwise a human
200 readable string message indicating why validation failed.
201 """
202 msg = validate_string(data, max_len=max_len)
203 if msg:
204 return msg
205 if not data.strip():
206 msg = "'%s' Blank strings are not permitted"
207 LOG.debug(msg, data)
208 return _(msg) % data
209
210
211 def validate_string_or_none(data, max_len=None):
212 """Validate data is a string or None.
213
214 :param data: The data to validate.
215 :param max_len: An optional cap on the length of the string data.
216 :returns: None if the data is None or a valid string, otherwise a human
217 readable message indicating why validation failed.
218 """
219 if data is not None:
220 return validate_string(data, max_len=max_len)
221
222
223 def validate_string(data, max_len=None):
224 """Validate data is a string object optionally capping it length.
225
226 :param data: The data to validate.
227 :param max_len: An optional cap on the length of the string.
228 :returns: None if the data is a valid string type and (optionally) within
229 the given max_len. Otherwise a human readable message indicating why
230 the data is invalid.
231 """
232 if not isinstance(data, str):
233 msg = "'%s' is not a valid string"
234 LOG.debug(msg, data)
235 return _(msg) % data
236
237 if max_len is not None and len(data) > max_len:
238 msg_data = {'data': data, 'max_len': max_len}
239 msg = "'%(data)s' exceeds maximum length of %(max_len)s"
240 LOG.debug(msg, msg_data)
241 return _(msg) % msg_data
242
243
244 _validate_list_of_unique_strings = functools.partial(_validate_list_of_items,
245 validate_string)
246
247
248 # NOTE(boden): stubbed out for docstring comments.
249 def validate_list_of_unique_strings(data, max_len=None):
250 """Validate data is a list of unique strings.
251
252 :param data: The data to validate.
253 :param max_len: An optional cap on the length of the string.
254 :returns: None if the data is a list of non-empty/non-blank strings,
255 otherwise a human readable message indicating why validation failed.
256 """
257 return _validate_list_of_unique_strings(data, max_len=max_len)
258
259
260 def validate_oneline_not_empty_string(data, max_len=None):
261 """Validate data is a non-empty string without newline character.
262
263 :param data: The data to validate.
264 :param max_len: An optional cap on the length of the string.
265 :returns: None if the data is a string without newline character,
266 otherwise a human readable message indicating why validation failed.
267 """
268 msg = validate_not_empty_string(data, max_len=max_len)
269 if msg:
270 return msg
271 if len(data.splitlines()) > 1:
272 msg = "Multi-line string is not allowed: '%s'"
273 LOG.debug(msg, data)
274 return _(msg) % data
275
276
277 def validate_oneline_not_empty_string_or_none(data, max_len=None):
278 """Validate data is a non-empty string without newline character or None.
279
280 :param data: The data to validate.
281 :param max_len: An optional cap on the length of the string data.
282 :returns: None if the data is None or a valid string without newline
283 character, otherwise a human readable message indicating why
284 validation failed.
285 """
286 if data is not None:
287 return validate_oneline_not_empty_string(data, max_len=max_len)
288
289
290 def validate_boolean(data, valid_values=None):
291 """Validate data is a python bool compatible object.
292
293 :param data: The data to validate.
294 :param valid_values: Not used!
295 :return: None if the value can be converted to a bool, otherwise a
296 human readable message indicating why data is invalid.
297 """
298 try:
299 strutils.bool_from_string(data, strict=True)
300 except ValueError:
301 msg = "'%s' is not a valid boolean value"
302 LOG.debug(msg, data)
303 return _(msg) % data
304
305
306 def validate_integer(data, valid_values=None):
307 """This function validates if the data is an integer.
308
309 It checks both number or string provided to validate it's an
310 integer and returns a message with the error if it's not
311
312 :param data: The string or number to validate as integer.
313 :param valid_values: values to limit the 'data' to.
314 :returns: None if data is an integer, otherwise a human readable message
315 indicating why validation failed..
316 """
317
318 if valid_values is not None:
319 msg = validate_values(data=data, valid_values=valid_values)
320 if msg:
321 return msg
322
323 msg = "'%s' is not an integer"
324 try:
325 fl_n = float(data)
326 int_n = int(data)
327 except (ValueError, TypeError, OverflowError):
328 LOG.debug(msg, data)
329 return _(msg) % data
330
331 # Fail test if non equal or boolean
332 if fl_n != int_n:
333 LOG.debug(msg)
334 return _(msg) % data
335 elif isinstance(data, bool):
336 msg = "'%s' is not an integer:boolean"
337 LOG.debug(msg, data)
338 return _(msg) % data
339
340
341 def validate_range(data, valid_values=None):
342 """Check that integer value is within a range provided.
343
344 Test is inclusive. Allows either limit to be ignored, to allow
345 checking ranges where only the lower or upper limit matter.
346 It is expected that the limits provided are valid integers or
347 the value None.
348
349 :param data: The data to validate.
350 :param valid_values: A list of 2 elements where element 0 is the min
351 value the int data can have and element 1 is the max.
352 :returns: None if the data is a valid int in the given range, otherwise
353 a human readable message as to why validation failed.
354 """
355
356 min_value = valid_values[0]
357 max_value = valid_values[1]
358 try:
359 data = int(data)
360 except (ValueError, TypeError):
361 msg = "'%s' is not an integer"
362 LOG.debug(msg, data)
363 return _(msg) % data
364 if min_value is not UNLIMITED and data < min_value:
365 msg_data = {'data': data, 'limit': min_value}
366 msg = "'%(data)s' is too small - must be at least '%(limit)d'"
367 LOG.debug(msg, msg_data)
368 return _(msg) % msg_data
369 if max_value is not UNLIMITED and data > max_value:
370 msg_data = {'data': data, 'limit': max_value}
371 msg = "'%(data)s' is too large - must be no larger than '%(limit)d'"
372 LOG.debug(msg, msg_data)
373 return _(msg) % msg_data
374
375
376 def validate_range_or_none(data, valid_values=None):
377 """Check that the provided value is none or a ranged integer"""
378
379 if data is not None:
380 return validate_range(data, valid_values)
381
382
383 def validate_no_whitespace(data):
384 """Validates that input has no whitespace.
385
386 :param data: The data to validate. Must be a python string type suitable
387 for searching via regex.
388 :returns: The data itself.
389 :raises InvalidInput: If the data contains whitespace.
390 """
391 if re.search(r'\s', data):
392 msg = "'%s' contains whitespace"
393 LOG.debug(msg, data)
394 raise n_exc.InvalidInput(error_message=_(msg) % data)
395 return data
396
397
398 def validate_mac_address(data, valid_values=None):
399 """Validate data is a MAC address.
400
401 :param data: The data to validate.
402 :param valid_values: Not used!
403 :returns: None if the data is a valid MAC address, otherwise a human
404 readable message as to why validation failed.
405 """
406 try:
407 valid_mac = netaddr.valid_mac(validate_no_whitespace(data))
408 except Exception:
409 valid_mac = False
410
411 if valid_mac:
412 valid_mac = (netaddr.EUI(data) not in
413 map(netaddr.EUI, constants.INVALID_MAC_ADDRESSES))
414 # TODO(arosen): The code in this file should be refactored
415 # so it catches the correct exceptions. validate_no_whitespace
416 # raises AttributeError if data is None.
417 if not valid_mac:
418 msg = "'%s' is not a valid MAC address"
419 LOG.debug(msg, data)
420 return _(msg) % data
421
422
423 def validate_mac_address_or_none(data, valid_values=None):
424 """Validate data is a MAC address if the data isn't None.
425
426 :param data: The data to validate.
427 :param valid_values: Not used!
428 :returns: None if the data is None or a valid MAC address, otherwise
429 a human readable message indicating why validation failed.
430 """
431 if data is not None:
432 return validate_mac_address(data, valid_values)
433
434
435 def validate_ip_address(data, valid_values=None):
436 """Validate data is an IP address.
437
438 :param data: The data to validate.
439 :param valid_values: Not used!
440 :returns: None if data is an IP address, otherwise a human readable
441 message indicating why data isn't an IP address.
442 """
443 msg = None
444 msg_data = data
445 try:
446 try:
447 # netaddr.core.ZEROFILL is only applicable to IPv4.
448 # it will remove leading zeros from IPv4 address octets.
449 ip = netaddr.IPAddress(validate_no_whitespace(data),
450 flags=netaddr.core.ZEROFILL)
451 except ValueError:
452 # It could be an IPv6 address and netaddr.core.ZEROFILL flag
453 # cannot be used in netaddr>=1.0.0
454 ip = netaddr.IPAddress(validate_no_whitespace(data))
455 # The followings are quick checks for IPv6 (has ':') and
456 # IPv4. (has 3 periods like 'xx.xx.xx.xx')
457 # NOTE(yamamoto): netaddr uses libraries provided by the underlying
458 # platform to convert addresses. For example, inet_aton(3).
459 # Some platforms, including NetBSD and OS X, have inet_aton
460 # implementation which accepts more varying forms of addresses than
461 # we want to accept here. The following check is to reject such
462 # addresses. For Example:
463 # >>> netaddr.IPAddress('1' * 59)
464 # IPAddress('199.28.113.199')
465 # >>> netaddr.IPAddress(str(int('1' * 59) & 0xffffffff))
466 # IPAddress('199.28.113.199')
467 # >>>
468 if ':' not in data and data.count('.') != 3:
469 msg = "'%s' is not a valid IP address"
470 # A leading '0' in IPv4 address may be interpreted as an octal number,
471 # e.g. 011 octal is 9 decimal. Since there is no standard saying
472 # whether IP address with leading '0's should be interpreted as octal
473 # or decimal, hence we reject leading '0's to avoid ambiguity.
474 elif ip.version == 4 and str(ip) != data:
475 msg_data = {"data": data, "ip": ip}
476 msg = ("'%(data)s' is not an accepted IP address, "
477 "'%(ip)s' is recommended")
478 except Exception:
479 msg = "'%s' is not a valid IP address"
480 if msg:
481 LOG.debug(msg, msg_data)
482 msg = _(msg) % msg_data
483 return msg
484
485
486 def _validate_any_key_spec(data, key_specs=None):
487 """Validate a dict matches at least 1 key spec.
488
489 :param data: The dict to validate.
490 :param key_specs: An iterable collection of key spec dicts used to validate
491 data.
492 :returns: None if at least 1 of the key_specs matches data, otherwise
493 a message is returned indicating data could not be matched with any
494 of the key_specs.
495 """
496 for spec in key_specs:
497 if validate_dict(data, spec) is None:
498 return None
499 msg = "No valid key specs matched for: %s"
500 LOG.debug(msg, data)
501 return _(msg) % data
502
503
504 def validate_any_key_specs_or_none(data, key_specs=None):
505 """Validate each dict in a list matches at least 1 key_spec.
506
507 :param data: The list of dicts to validate.
508 :param key_specs: An iterable collection of key spec dicts that is used
509 to check each dict in data.
510 :returns: None.
511 :raises InvalidInput: If any of the dicts in data do not match at least
512 1 of the key_specs given.
513 """
514 if data is None:
515 return
516
517 def dict_validator(data_dict):
518 msg = _validate_any_key_spec(data_dict, key_specs=key_specs)
519 if msg:
520 raise n_exc.InvalidInput(error_message=msg)
521
522 msg = _validate_list_of_items(dict_validator, data)
523 if msg:
524 raise n_exc.InvalidInput(error_message=msg)
525
526
527 def validate_ip_pools(data, valid_values=None):
528 """Validate that start and end IP addresses are present.
529
530 In addition to this the IP addresses will also be validated.
531
532 :param data: The data to validate. Must be a list-like structure of
533 IP pool dicts that each have a 'start' and 'end' key value.
534 :param valid_values: Not used!
535 :returns: None if data is a valid list of IP pools, otherwise a message
536 indicating why the data is invalid.
537 """
538 if not isinstance(data, list):
539 msg = "Invalid data format for IP pool: '%s'"
540 LOG.debug(msg, data)
541 return _(msg) % data
542
543 expected_keys = ['start', 'end']
544 for ip_pool in data:
545 msg = _verify_dict_keys(expected_keys, ip_pool)
546 if msg:
547 return msg
548 for k in expected_keys:
549 msg = validate_ip_address(ip_pool[k])
550 if msg:
551 return msg
552
553
554 def validate_fixed_ips(data, valid_values=None):
555 """Validate data is a list of fixed IP dicts.
556
557 In addition this function validates the ip_address and subnet_id
558 if present in each fixed IP dict.
559
560 :param data: The data to validate.
561 :param valid_values: Not used!
562 :returns: None if data is a valid list of fixed IP dicts. Otherwise a
563 human readable message is returned indicating why validation failed.
564 """
565 if not isinstance(data, list):
566 msg = "Invalid data format for fixed IP: '%s'"
567 LOG.debug(msg, data)
568 return _(msg) % data
569
570 ips = []
571 for fixed_ip in data:
572 if not isinstance(fixed_ip, dict):
573 msg = "Invalid data format for fixed IP: '%s'"
574 LOG.debug(msg, fixed_ip)
575 return _(msg) % fixed_ip
576 if 'ip_address' in fixed_ip:
577 # Ensure that duplicate entries are not set - just checking IP
578 # suffices. Duplicate subnet_id's are legitimate.
579 fixed_ip_address = fixed_ip['ip_address']
580 if fixed_ip_address in ips:
581 msg = "Duplicate IP address '%s'"
582 LOG.debug(msg, fixed_ip_address)
583 msg = _(msg) % fixed_ip_address
584 else:
585 msg = validate_ip_address(fixed_ip_address)
586 if msg:
587 return msg
588 ips.append(fixed_ip_address)
589 if 'subnet_id' in fixed_ip:
590 msg = validate_uuid(fixed_ip['subnet_id'])
591 if msg:
592 return msg
593
594
595 def validate_nameservers(data, valid_values=None):
596 """Validate a list of unique IP addresses.
597
598 :param data: The data to validate.
599 :param valid_values: Not used!
600 :returns: None if data is a list of valid IP addresses, otherwise
601 a human readable message is returned indicating why validation failed.
602 """
603 if not hasattr(data, '__iter__'):
604 msg = "Invalid data format for nameserver: '%s'"
605 LOG.debug(msg, data)
606 return _(msg) % data
607
608 hosts = []
609 for host in data:
610 # This must be an IP address only
611 msg = validate_ip_address(host)
612 if msg:
613 msg_data = {'host': host, 'msg': msg}
614 msg = "'%(host)s' is not a valid nameserver. %(msg)s"
615 LOG.debug(msg, msg_data)
616 return _(msg) % msg_data
617 if host in hosts:
618 msg = "Duplicate nameserver '%s'"
619 LOG.debug(msg, host)
620 return _(msg) % host
621 hosts.append(host)
622
623
624 def validate_hostroutes(data, valid_values=None):
625 """Validate a list of unique host route dicts.
626
627 :param data: The data to validate. To be valid it must be a list like
628 structure of host route dicts, each containing 'destination' and
629 'nexthop' key values.
630 :param valid_values: Not used!
631 :returns: None if data is a valid list of unique host route dicts,
632 otherwise a human readable message indicating why validation failed.
633 """
634 if not isinstance(data, list):
635 msg = "Invalid data format for hostroute: '%s'"
636 LOG.debug(msg, data)
637 return _(msg) % data
638
639 expected_keys = ['destination', 'nexthop']
640 hostroutes = []
641 for hostroute in data:
642 msg = _verify_dict_keys(expected_keys, hostroute)
643 if msg:
644 return msg
645 msg = validate_route_cidr(hostroute['destination'])
646 if msg:
647 return msg
648 msg = validate_ip_address(hostroute['nexthop'])
649 if msg:
650 return msg
651 if hostroute in hostroutes:
652 msg = "Duplicate hostroute '%s'"
653 LOG.debug(msg, hostroute)
654 return _(msg) % hostroute
655 hostroutes.append(hostroute)
656
657
658 def validate_ip_address_or_none(data, valid_values=None):
659 """Validate data is an IP address or None.
660
661 :param data: The data to validate.
662 :param valid_values: An optional list of values data may take on.
663 :return: None if data is None or a valid IP address, otherwise a
664 human readable message indicating why the data is invalid.
665 """
666 if data is not None:
667 return validate_ip_address(data, valid_values)
668
669
670 def validate_ip_or_subnet_or_none(data, valid_values=None):
671 """Validate data is an IP address, a valid IP subnet string, or None.
672
673 :param data: The data to validate.
674 :param valid_values: Not used!
675 :return: None if data is None or a valid IP address or a valid IP subnet,
676 otherwise a human readable message indicating why the data is neither
677 an IP address nor IP subnet.
678 """
679 msg_ip = validate_ip_address_or_none(data)
680 msg_subnet = validate_subnet_or_none(data)
681 if msg_ip is not None and msg_subnet is not None:
682 return _("'%(data)s' is neither a valid IP address, nor "
683 "is it a valid IP subnet") % {'data': data}
684
685
686 def validate_subnet(data, valid_values=None):
687 """Validate data is an IP network subnet string.
688
689 :param data: The data to validate.
690 :param valid_values: Not used!
691 :returns: None if data is valid IP network address. Otherwise a human
692 readable message as to why data is invalid.
693 """
694 try:
695 net = netaddr.IPNetwork(validate_no_whitespace(data))
696 # TODO(ihar): remove this explicit check when the minimal version of
697 # netaddr is 1.0.0 that enforces the input format more strictly
698 if '/' not in data or (net.version == 4 and str(net) != data):
699 raise n_exc.InvalidInput
700 except Exception:
701 msg = "'%s' is not a valid IP subnet"
702 LOG.debug(msg, data)
703 return _(msg) % data
704
705
706 def validate_route_cidr(data, valid_values=None):
707 """Validate data is a proper CIDR string.
708
709 :param data: The data to validate.
710 :param valid_values: Not used!
711 :returns: None if data is valid CIDR. Otherwise a human
712 readable message as to why data is invalid.
713 """
714 msg = "'%s' is not a valid CIDR"
715 try:
716 net = netaddr.IPNetwork(validate_no_whitespace(data))
717 # TODO(ihar): remove this explicit check when the minimal version of
718 # netaddr is 1.0.0 that enforces the input format more strictly
719 if '/' not in data or (net.network != net.ip):
720 raise n_exc.InvalidInput
721 if net.is_loopback():
722 msg = "'%s' is not a routable CIDR"
723 raise n_exc.InvalidInput
724 except Exception:
725 LOG.debug(msg, data)
726 return _(msg) % data
727
728
729 def validate_subnet_or_none(data, valid_values=None):
730 """Validate data is a valid subnet address string or None.
731
732 :param data: The data to validate.
733 :param valid_values: The optional list of values data may take on.
734 :returns: None if data is None or a valid subnet, otherwise a human
735 readable message as to why data is invalid.
736 """
737 if data is not None:
738 return validate_subnet(data, valid_values)
739
740
741 _validate_subnet_list = functools.partial(_validate_list_of_items,
742 validate_subnet)
743
744
745 # NOTE(boden): subbed out for docstring comments.
746 def validate_subnet_list(data, valid_values=None):
747 """Validate data is a list of subnet dicts.
748
749 :param data: The data to validate.
750 :param valid_values: Not used!
751 :returns: None if data is a valid list of subnet dicts, otherwise a human
752 readable message as to why the data is invalid.
753 """
754 return _validate_subnet_list(data, valid_values)
755
756
757 def validate_subnet_list_or_none(data, key_specs=None):
758 """Validate data is a list of subnet dicts or None.
759
760 :param data: The data to validate.
761 :param key_specs: Not used!
762 :returns: None if data is None or a valid list of subnet dicts, otherwise
763 a human readable message as to why the data is invalid.
764 """
765 if data is not None:
766 return validate_subnet_list(data, key_specs)
767
768
769 def validate_regex(data, valid_values=None):
770 """Validate data is matched against a regex.
771
772 :param data: The data to validate.
773 :param valid_values: The regular expression to use with re.match on
774 the data.
775 :returns: None if data contains matches for valid_values, otherwise a
776 human readable message as to why data is invalid.
777 """
778 try:
779 if re.match(valid_values, data):
780 return
781 except TypeError:
782 pass
783
784 msg = "'%s' is not a valid input"
785 LOG.debug(msg, data)
786 return _(msg) % data
787
788
789 def validate_regex_or_none(data, valid_values=None):
790 """Validate data is None or matched against a regex.
791
792 :param data: The data to validate.
793 :param valid_values: The regular expression to use with re.match on
794 the data.
795 :returns: None if data is None or contains matches for valid_values,
796 otherwise a human readable message as to why data is invalid.
797 """
798 if data is not None:
799 return validate_regex(data, valid_values)
800
801
802 def validate_list_of_regex_or_none(data, valid_values=None):
803 """Validate data is None or a list of items matching regex.
804
805 :param data: A list of data to validate.
806 :param valid_values: The regular expression to use with re.match on
807 each element of the data.
808 :returns: None if data is None or contains matches for valid_values,
809 otherwise a human readable message as to why data is invalid.
810 """
811 if data is not None:
812 return _validate_list_of_items(validate_regex, data, valid_values)
813
814
815 def validate_subnetpool_id(data, valid_values=None):
816 """Validate data is valid subnet pool ID.
817
818 :param data: The data to validate.
819 :param valid_values: Not used!
820 :returns: None if data is a valid subnet pool ID, otherwise a
821 human readable message as to why it's invalid.
822 """
823 if data != constants.IPV6_PD_POOL_ID:
824 return validate_uuid_or_none(data, valid_values)
825
826
827 def validate_subnetpool_id_or_none(data, valid_values=None):
828 """Validate data is valid subnet pool ID or None.
829
830 :param data: The data to validate.
831 :param valid_values: Not used!
832 :returns: None if data is a valid subnet pool ID or None, otherwise a
833 human readable message as to why it's invalid.
834 """
835 if data is not None:
836 return validate_subnetpool_id(data, valid_values)
837
838
839 def validate_uuid(data, valid_values=None):
840 """Validate data is UUID like.
841
842 :param data: The data to validate.
843 :param valid_values: Not used!
844 :returns: None if data is UUID like in form, otherwise a human readable
845 message indicating why data is invalid.
846 """
847 if not uuidutils.is_uuid_like(data):
848 msg = "'%s' is not a valid UUID"
849 LOG.debug(msg, data)
850 return _(msg) % data
851
852
853 def validate_uuid_or_none(data, valid_values=None):
854 """Validate data is UUID like or None.
855
856 :param data: The data to validate.
857 :param valid_values: Not used!
858 :returns: None if data is UUID like in form or None, otherwise a human
859 readable message indicating why data is invalid.
860 """
861 if data is not None:
862 return validate_uuid(data)
863
864
865 _validate_uuid_list = functools.partial(_validate_list_of_items,
866 validate_uuid)
867
868
869 # NOTE(boden): subbed out for docstring comments.
870 def validate_uuid_list(data, valid_values=None):
871 """Validate data is a list of UUID like values.
872
873 :param data: The data to validate.
874 :param valid_values: Not used!
875 :returns: None if data is an iterable that contains valid UUID values,
876 otherwise a message is returned indicating why validation failed.
877 """
878 return _validate_uuid_list(data, valid_values)
879
880
881 def validate_uuid_list_non_empty(data, valid_values=None):
882 """Validate data is a non-empty list of UUID like values.
883
884 :param data: The data to validate.
885 :param valid_values: Not used!
886 :returns: None if data is a non-empty iterable that contains valid UUID
887 values, otherwise a message is returned indicating why validation
888 failed.
889 """
890 return _validate_list_of_items_non_empty(validate_uuid, data)
891
892
893 def _extract_validator(key_validator):
894 # Find validator function in key validation spec
895 #
896 # TODO(salv-orlando): Structure of dict attributes should be improved
897 # to avoid iterating over items
898 for (k, v) in key_validator.items():
899 if k.startswith('type:'):
900 (validator_name, validator_params) = (k, v)
901 try:
902 return (validator_name,
903 validators[validator_name],
904 validator_params)
905 except KeyError as e:
906 raise UndefinedValidator(validator_name) from e
907 return None, None, None
908
909
910 def _validate_dict_item(key, key_validator, data):
911 # Find conversion function, if any, and apply it
912 conv_func = key_validator.get('convert_to')
913 if conv_func:
914 data[key] = conv_func(data.get(key))
915 try:
916 dummy_, val_func, val_params = _extract_validator(key_validator)
917 if val_func:
918 return val_func(data.get(key), val_params)
919 # NOTE(tmorin): here we silently omit to validate a key for which
920 # no type validator has been defined
921 except UndefinedValidator as e:
922 # NOTE(tmorin): Should we really return an API error on such
923 # an issue. Wouldn't InternalServer error be more natural ?
924 LOG.debug(e.message)
925 return e.message
926
927
928 def validate_dict(data, key_specs=None):
929 """Validate data is a dict optionally containing a specific set of keys.
930
931 :param data: The data to validate.
932 :param key_specs: The optional list of keys that must be contained in
933 data.
934 :returns: None if data is a dict and (optionally) contains only key_specs.
935 Otherwise a human readable message is returned indicating why data is
936 not valid.
937 """
938 if not isinstance(data, dict):
939 msg = "'%s' is not a dictionary"
940 LOG.debug(msg, data)
941 return _(msg) % data
942 # Do not perform any further validation, if no constraints are supplied
943 if not key_specs:
944 return
945
946 # Check whether all required keys are present
947 required_keys = [key for key, spec in key_specs.items()
948 if spec.get('required')]
949
950 if required_keys:
951 msg = _verify_dict_keys(required_keys, data, False)
952 if msg:
953 return msg
954
955 # Check whether unexpected keys are supplied in data
956 unexpected_keys = [key for key in data if key not in key_specs]
957 if unexpected_keys:
958 msg_data = ', '.join(unexpected_keys)
959 msg = "Unexpected keys supplied: %s"
960 LOG.debug(msg, msg_data)
961 return _(msg) % msg_data
962
963 # Perform validation and conversion of all values
964 # according to the specifications.
965 for key, key_validator in [(k, v) for k, v in key_specs.items()
966 if k in data]:
967 msg = _validate_dict_item(key, key_validator, data)
968 if msg:
969 return msg
970
971
972 def validate_dict_or_none(data, key_specs=None):
973 """Validate data is None or a dict containing a specific set of keys.
974
975 :param data: The data to validate.
976 :param key_specs: The optional list of keys that must be contained in
977 data.
978 :returns: None if data is None or a dict that (optionally) contains
979 all key_specs. Otherwise a human readable message is returned
980 indicating why data is not valid.
981 """
982 if data is not None:
983 return validate_dict(data, key_specs)
984
985
986 def validate_dict_or_empty(data, key_specs=None):
987 """Validate data is {} or a dict containing a specific set of keys.
988
989 :param data: The data to validate.
990 :param key_specs: The optional list of keys that must be contained in
991 data.
992 :returns: None if data is {} or a dict (optionally) containing
993 only key_specs. Otherwise a human readable message is returned
994 indicating why data is not valid.
995 """
996 if data != {}:
997 return validate_dict(data, key_specs)
998
999
1000 def validate_dict_or_nodata(data, key_specs=None):
1001 """Validate no data or a dict containing a specific set of keys.
1002
1003 :param data: The data to validate. May be None.
1004 :param key_specs: The optional list of keys that must be contained in
1005 data.
1006 :returns: None if no data/empty dict or a dict and (optionally) contains
1007 all key_specs. Otherwise a human readable message is returned
1008 indicating why data is not valid.
1009 """
1010 if data:
1011 return validate_dict(data, key_specs)
1012
1013
1014 def validate_non_negative(data, valid_values=None):
1015 """Validate data is a positive int.
1016
1017 :param data: The data to validate
1018 :param valid_values: Not used!
1019 :returns: None if data is an int and is positive, otherwise a human
1020 readable message as to why data is invalid.
1021 """
1022 try:
1023 data = int(data)
1024 except (ValueError, TypeError):
1025 msg = "'%s' is not an integer"
1026 LOG.debug(msg, data)
1027 return _(msg) % data
1028
1029 if data < 0:
1030 msg = "'%s' should be non-negative"
1031 LOG.debug(msg, data)
1032 return _(msg) % data
1033
1034
1035 def validate_port_range_or_none(data, valid_values=None):
1036 """Validate data is a range of TCP/UDP port numbers
1037
1038 :param data: The data to validate
1039 :param valid_values: valid port range, default is [0, 65535]
1040 :returns: None if data is a valid port between the values defined in the
1041 valid_values param, or two valid ports between the values defined in
1042 the valid_values param with a colon between them, otherwise a human
1043 readable message as to why data is invalid.
1044 """
1045 if data is None:
1046 return
1047
1048 min_value, max_value = valid_values or [0, 65535]
1049
1050 data = str(data)
1051 ports = data.split(':')
1052 if len(ports) > 2:
1053 msg = "Port range must be two integers separated by a colon"
1054 LOG.debug(msg)
1055 return _(msg)
1056 for p in ports:
1057 if len(p) == 0:
1058 msg = "Port range must be two integers separated by a colon"
1059 LOG.debug(msg)
1060 return _(msg)
1061 if not netutils.is_valid_port(p):
1062 msg = "Invalid port: %s"
1063 LOG.debug(msg, p)
1064 return _(msg) % p
1065 if max_value < int(p) or int(p) < min_value:
1066 msg = "Invalid port: %s, the port must be in the range [%s, %s]"
1067 LOG.debug(msg, p, min_value, max_value)
1068 return _(msg) % (p, min_value, max_value)
1069 if len(ports) > 1 and int(ports[0]) > int(ports[1]):
1070 msg = "First port in a port range must be lower than the second port"
1071 LOG.debug(msg)
1072 return _(msg)
1073
1074
1075 def validate_subports(data, valid_values=None):
1076 """Validate data is a list of subnet port dicts.
1077
1078 :param data: The data to validate.
1079 :param valid_values: Not used!
1080 :returns: None if data is a list of subport dicts each with a unique valid
1081 port_id, segmentation_id and segmentation_type. Otherwise a human
1082 readable message is returned indicating why the data is invalid.
1083 """
1084 if not isinstance(data, list):
1085 msg = "Invalid data format for subports: '%s' is not a list"
1086 LOG.debug(msg, data)
1087 return _(msg) % data
1088
1089 subport_ids = set()
1090 segmentations = collections.defaultdict(set)
1091 for subport in data:
1092 if not isinstance(subport, dict):
1093 msg = "Invalid data format for subport: '%s' is not a dict"
1094 LOG.debug(msg, subport)
1095 return _(msg) % subport
1096
1097 # Expect a non duplicated and valid port_id for the subport
1098 if 'port_id' not in subport:
1099 msg = "A valid port UUID must be specified"
1100 LOG.debug(msg)
1101 return _(msg)
1102 elif validate_uuid(subport["port_id"]):
1103 msg = _("Invalid UUID for subport: '%s'") % subport["port_id"]
1104 return msg
1105 elif subport["port_id"] in subport_ids:
1106 msg = _("Non unique UUID for subport: '%s'") % subport["port_id"]
1107 return msg
1108 subport_ids.add(subport["port_id"])
1109
1110 # Validate that both segmentation ID and segmentation type are
1111 # specified, and that the client does not duplicate segmentation
1112 # IDs (unless it is explicitly asked to inherit segmentation
1113 # details from the underlying subport's network).
1114 segmentation_type = subport.get("segmentation_type")
1115 if segmentation_type == 'inherit':
1116 return
1117 segmentation_id = subport.get("segmentation_id")
1118 if ((not segmentation_type or segmentation_id is None) and
1119 len(subport) > 1):
1120 msg = ("Invalid subport details '%s': missing segmentation "
1121 "information. Must specify both segmentation_id and "
1122 "segmentation_type")
1123 LOG.debug(msg, subport)
1124 return _(msg) % subport
1125 if segmentation_id in segmentations.get(segmentation_type, []):
1126 msg_data = {"seg_id": segmentation_id,
1127 "subport": subport["port_id"]}
1128 msg = ("Segmentation ID '%(seg_id)s' for '%(subport)s' is not "
1129 "unique")
1130 LOG.debug(msg, msg_data)
1131 return _(msg) % msg_data
1132 if segmentation_id is not None:
1133 segmentations[segmentation_type].add(segmentation_id)
1134
1135
1136 def validate_service_plugin_type(data, valid_values=None):
1137 """Validates data is a valid service plugin.
1138
1139 :param data: The service plugin type to validate.
1140 :param valid_values: Not used.
1141 :returns: None if data is a valid service plugin known to the plugin
1142 directory.
1143 :raises: InvalidServiceType if data is not a service known by the
1144 plugin directory.
1145 """
1146 if not directory.get_plugin(data):
1147 raise n_exc.InvalidServiceType(service_type=data)
1148
1149
1150 def validate_subnet_service_types(service_types, valid_values=None):
1151 if service_types:
1152 if not isinstance(service_types, list):
1153 raise exc.HTTPBadRequest(
1154 _("Subnet service types must be a list."))
1155
1156 # Include standard prefixes
1157 prefixes = list(constants.DEVICE_OWNER_PREFIXES)
1158 prefixes += constants.DEVICE_OWNER_COMPUTE_PREFIX
1159
1160 for service_type in service_types:
1161 if not isinstance(service_type, str):
1162 raise n_exc.InvalidInputSubnetServiceType(
1163 service_type=service_type)
1164 if not service_type.startswith(tuple(prefixes)):
1165 raise n_exc.InvalidSubnetServiceType(service_type=service_type)
1166
1167
1168 def validate_ethertype(ethertype, valid_values=None):
1169 """Validates ethertype is a valid ethertype.
1170
1171 :param ethertype: Ethertype to validate.
1172 :returns: None if data is a valid ethertype. Otherwise a human-readable
1173 message indicating that the data is not a valid ethertype.
1174 """
1175
1176 if cfg.CONF.sg_filter_ethertypes:
1177 os_ken_ethertypes = ether_types.__dict__
1178 try:
1179 # Use the ethertype constants from os_ken with the special
1180 # exception of 'IPv4', which appears as 'ETH_TYPE_IP' in os_ken.
1181 # Be case-insensitive.
1182 ethertype_str = str(ethertype).upper()
1183 if ethertype_str == "IPV4":
1184 ethertype_str = "IP"
1185 ethertype_name = 'ETH_TYPE_' + ethertype_str
1186 ethertype = os_ken_ethertypes.get(ethertype_name, ethertype)
1187 except TypeError:
1188 # Value of ethertype cannot be coerced into a string, like None
1189 pass
1190 try:
1191 if isinstance(ethertype, str):
1192 ethertype = int(ethertype, 16)
1193 if (isinstance(ethertype, int) and
1194 constants.ETHERTYPE_MIN <= ethertype <=
1195 constants.ETHERTYPE_MAX):
1196 return None
1197 except ValueError:
1198 pass
1199 msg = ("Ethertype %s is not a two octet hexadecimal "
1200 "number or ethertype name.")
1201 LOG.debug(msg, ethertype)
1202 return _(msg) % ethertype
1203 else:
1204 if ethertype in constants.VALID_ETHERTYPES:
1205 return None
1206 valids = ','.join(map(str, constants.VALID_ETHERTYPES))
1207 msg_data = {'ethertype': ethertype, 'valid_ethertypes': valids}
1208 msg = ("Ethertype %(ethertype)s is not a valid ethertype, must be "
1209 "one of %(valid_ethertypes)s.")
1210 LOG.debug(msg, msg_data)
1211 return _(msg) % msg_data
1212
1213
1214 def validate_list_of_dict_or_nodata(data, valid_values=None):
1215 """Validate a list of dictionaries.
1216
1217 :param data: The data to validate. The data could be an empty list or None.
1218 :param valid_values: The optional list of keys that must be contained in
1219 data.
1220 :returns: None if valid, error string otherwise.
1221 """
1222 if data:
1223 return _validate_list_of_items(validate_dict_or_nodata, data,
1224 **valid_values)
1225
1226
1227 # Dictionary that maintains a list of validation functions
1228 validators = {'type:dict': validate_dict,
1229 'type:dict_or_none': validate_dict_or_none,
1230 'type:dict_or_empty': validate_dict_or_empty,
1231 'type:dict_or_nodata': validate_dict_or_nodata,
1232 'type:ethertype': validate_ethertype,
1233 'type:fixed_ips': validate_fixed_ips,
1234 'type:hostroutes': validate_hostroutes,
1235 'type:ip_address': validate_ip_address,
1236 'type:ip_address_or_none': validate_ip_address_or_none,
1237 'type:ip_or_subnet_or_none': validate_ip_or_subnet_or_none,
1238 'type:ip_pools': validate_ip_pools,
1239 'type:list_of_regex_or_none': validate_list_of_regex_or_none,
1240 'type:mac_address': validate_mac_address,
1241 'type:mac_address_or_none': validate_mac_address_or_none,
1242 'type:nameservers': validate_nameservers,
1243 'type:non_negative': validate_non_negative,
1244 'type:port_range': validate_port_range_or_none,
1245 'type:range': validate_range,
1246 'type:range_or_none': validate_range_or_none,
1247 'type:regex': validate_regex,
1248 'type:regex_or_none': validate_regex_or_none,
1249 'type:string': validate_string,
1250 'type:string_or_none': validate_string_or_none,
1251 'type:not_empty_string': validate_not_empty_string,
1252 'type:not_empty_string_or_none':
1253 validate_not_empty_string_or_none,
1254 'type:oneline_not_empty_string':
1255 validate_oneline_not_empty_string,
1256 'type:oneline_not_empty_string_or_none':
1257 validate_oneline_not_empty_string_or_none,
1258 'type:subnet': validate_subnet,
1259 'type:subnet_list': validate_subnet_list,
1260 'type:subnet_or_none': validate_subnet_or_none,
1261 'type:subnetpool_id': validate_subnetpool_id,
1262 'type:subnetpool_id_or_none': validate_subnetpool_id_or_none,
1263 'type:subports': validate_subports,
1264 'type:uuid': validate_uuid,
1265 'type:uuid_or_none': validate_uuid_or_none,
1266 'type:uuid_list': validate_uuid_list,
1267 'type:uuid_list_non_empty': validate_uuid_list_non_empty,
1268 'type:values': validate_values,
1269 'type:boolean': validate_boolean,
1270 'type:integer': validate_integer,
1271 'type:list_of_unique_strings': validate_list_of_unique_strings,
1272 'type:list_of_any_key_specs_or_none':
1273 validate_any_key_specs_or_none,
1274 'type:service_plugin_type': validate_service_plugin_type,
1275 'type:list_of_subnets_or_none': validate_subnet_list_or_none,
1276 'type:list_of_subnet_service_types':
1277 validate_subnet_service_types,
1278 'type:list_of_dict_or_nodata': validate_list_of_dict_or_nodata,
1279 }
1280
1281
1282 class UndefinedValidator(Exception):
1283
1284 def __init__(self, validator_name):
1285 self.validator_name = validator_name
1286 self.message = _("Validator '%s' does not exist") % self.validator_name
1287
1288
1289 def _to_validation_type(validation_type):
1290 return (validation_type
1291 if validation_type.startswith('type:')
1292 else 'type:' + validation_type)
1293
1294
1295 def get_validator(validation_type, default=None):
1296 """Get a registered validator by type.
1297
1298 :param validation_type: The type to retrieve the validator for.
1299 :param default: A default value to return if the validator is
1300 not registered.
1301 :return: The validator if registered, otherwise the default value.
1302 """
1303 return validators.get(_to_validation_type(validation_type), default)
1304
1305
1306 def add_validator(validation_type, validator):
1307 """Dynamically add a validator.
1308
1309 This can be used by clients to add their own, private validators, rather
1310 than directly modifying the data structure. The clients can NOT modify
1311 existing validators.
1312 """
1313 key = _to_validation_type(validation_type)
1314 if key in validators:
1315 # NOTE(boden): imp.load_source() forces module reinitialization that
1316 # can lead to validator redefinition from the same call site
1317 if inspect.getsource(validator) != inspect.getsource(validators[key]):
1318 msg = _("Validator type %s is already defined") % validation_type
1319 raise KeyError(msg)
1320 return
1321 validators[key] = validator