urls.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. """Validation for URLs."""
  2. import re
  3. from wandb._pydantic import IS_PYDANTIC_V2
  4. def validate_url(url: object) -> None:
  5. """Validate a URL.
  6. Args:
  7. url: The URL to validate.
  8. Raises:
  9. ValueError: If the URL is invalid.
  10. TypeError: If given something other than a string.
  11. """
  12. if not isinstance(url, str):
  13. raise TypeError(f"Expected a string, got {type(url)}")
  14. if IS_PYDANTIC_V2:
  15. _validate_url_pydantic(url)
  16. else:
  17. _validate_url_custom(url)
  18. def _validate_url_pydantic(url: str) -> None:
  19. """Validate a URL using Pydantic's validator."""
  20. from pydantic_core import SchemaValidator, core_schema
  21. SchemaValidator(
  22. core_schema.url_schema(
  23. allowed_schemes=["http", "https"],
  24. strict=True,
  25. )
  26. ).validate_python(url)
  27. def _validate_url_custom(url: str) -> None:
  28. """Validate a URL.
  29. We will remove this once we can require Pydantic V2.
  30. Based on the Django URLValidator, but with a few additional checks.
  31. Copyright (c) Django Software Foundation and individual contributors.
  32. All rights reserved.
  33. Redistribution and use in source and binary forms, with or without modification,
  34. are permitted provided that the following conditions are met:
  35. 1. Redistributions of source code must retain the above copyright notice,
  36. this list of conditions and the following disclaimer.
  37. 2. Redistributions in binary form must reproduce the above copyright
  38. notice, this list of conditions and the following disclaimer in the
  39. documentation and/or other materials provided with the distribution.
  40. 3. Neither the name of Django nor the names of its contributors may be used
  41. to endorse or promote products derived from this software without
  42. specific prior written permission.
  43. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  44. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  45. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  46. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
  47. ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  48. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  49. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  50. ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  51. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  52. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  53. """
  54. from urllib.parse import urlparse, urlsplit
  55. ul = "\u00a1-\uffff" # Unicode letters range (must not be a raw string).
  56. # IP patterns
  57. ipv4_re = (
  58. r"(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)"
  59. r"(?:\.(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)){3}"
  60. )
  61. ipv6_re = r"\[[0-9a-f:.]+\]" # (simple regex, validated later)
  62. # Host patterns
  63. hostname_re = (
  64. r"[a-z" + ul + r"0-9](?:[a-z" + ul + r"0-9-]{0,61}[a-z" + ul + r"0-9])?"
  65. )
  66. # Max length for domain name labels is 63 characters per RFC 1034 sec. 3.1
  67. domain_re = r"(?:\.(?!-)[a-z" + ul + r"0-9-]{1,63}(?<!-))*"
  68. tld_re = (
  69. r"\." # dot
  70. r"(?!-)" # can't start with a dash
  71. r"(?:[a-z" + ul + "-]{2,63}" # domain label
  72. r"|xn--[a-z0-9]{1,59})" # or punycode label
  73. r"(?<!-)" # can't end with a dash
  74. r"\.?" # may have a trailing dot
  75. )
  76. # host_re = "(" + hostname_re + domain_re + tld_re + "|localhost)"
  77. # todo?: allow hostname to be just a hostname (no tld)?
  78. host_re = "(" + hostname_re + domain_re + f"({tld_re})?" + "|localhost)"
  79. regex = re.compile(
  80. r"^(?:[a-z0-9.+-]*)://" # scheme is validated separately
  81. r"(?:[^\s:@/]+(?::[^\s:@/]*)?@)?" # user:pass authentication
  82. r"(?:" + ipv4_re + "|" + ipv6_re + "|" + host_re + ")"
  83. r"(?::[0-9]{1,5})?" # port
  84. r"(?:[/?#][^\s]*)?" # resource path
  85. r"\Z",
  86. re.IGNORECASE,
  87. )
  88. schemes = {"http", "https"}
  89. unsafe_chars = frozenset("\t\r\n")
  90. scheme = url.split("://")[0].lower()
  91. split_url = urlsplit(url)
  92. parsed_url = urlparse(url)
  93. if parsed_url.netloc == "":
  94. raise ValueError(f"Invalid URL: {url!r}")
  95. elif unsafe_chars.intersection(url):
  96. raise ValueError("URL cannot contain unsafe characters")
  97. elif scheme not in schemes:
  98. raise ValueError("URL must start with `http(s)://`")
  99. elif not regex.search(url):
  100. raise ValueError(f"{url!r} is not a valid server address")
  101. elif split_url.hostname is None or len(split_url.hostname) > 253:
  102. raise ValueError("hostname is invalid")