data_backends.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import logging
  2. import re
  3. import tempfile
  4. from contextlib import contextmanager
  5. from pathlib import Path, PurePosixPath
  6. from urllib.parse import urlparse
  7. from django import forms
  8. from django.core.exceptions import ImproperlyConfigured
  9. from django.utils.translation import gettext_lazy as _
  10. from netbox.data_backends import DataBackend, register_data_backend
  11. from utilities.constants import HTTP_PROXY_SUPPORTED_SCHEMAS, HTTP_PROXY_SUPPORTED_SOCK_SCHEMAS
  12. from utilities.proxy import resolve_proxies
  13. from utilities.socks import ProxyPoolManager
  14. from .exceptions import SyncError
  15. __all__ = (
  16. 'GitBackend',
  17. 'LocalBackend',
  18. 'S3Backend',
  19. 'url_has_embedded_credentials',
  20. )
  21. logger = logging.getLogger('netbox.data_backends')
  22. def url_has_embedded_credentials(url):
  23. """
  24. Check if a URL contains embedded credentials (username in the URL).
  25. URLs like 'https://user@bitbucket.org/...' have embedded credentials.
  26. This is used to avoid passing explicit credentials to dulwich when the
  27. URL already contains them, which would cause authentication conflicts.
  28. """
  29. parsed = urlparse(url)
  30. return bool(parsed.username)
  31. @register_data_backend()
  32. class LocalBackend(DataBackend):
  33. name = 'local'
  34. label = _('Local')
  35. is_local = True
  36. @contextmanager
  37. def fetch(self):
  38. logger.debug("Data source type is local; skipping fetch")
  39. local_path = urlparse(self.url).path # Strip file:// scheme
  40. yield local_path
  41. @register_data_backend()
  42. class GitBackend(DataBackend):
  43. name = 'git'
  44. label = 'Git'
  45. parameters = {
  46. 'username': forms.CharField(
  47. required=False,
  48. label=_('Username'),
  49. widget=forms.TextInput(attrs={'class': 'form-control'}),
  50. help_text=_("Only used for cloning with HTTP(S)"),
  51. ),
  52. 'password': forms.CharField(
  53. required=False,
  54. label=_('Password'),
  55. widget=forms.TextInput(attrs={'class': 'form-control'}),
  56. help_text=_("Only used for cloning with HTTP(S)"),
  57. ),
  58. 'branch': forms.CharField(
  59. required=False,
  60. label=_('Branch'),
  61. widget=forms.TextInput(attrs={'class': 'form-control'})
  62. )
  63. }
  64. sensitive_parameters = ['password']
  65. def init_config(self):
  66. from dulwich.config import ConfigDict
  67. # Initialize backend config
  68. config = ConfigDict()
  69. self.socks_proxy = None
  70. # Apply HTTP proxy (if configured)
  71. proxies = resolve_proxies(url=self.url, context={'client': self}) or {}
  72. if proxy := proxies.get(self.url_scheme):
  73. if urlparse(proxy).scheme not in HTTP_PROXY_SUPPORTED_SCHEMAS:
  74. raise ImproperlyConfigured(f"Unsupported Git DataSource proxy scheme: {urlparse(proxy).scheme}")
  75. if self.url_scheme in ('http', 'https'):
  76. config.set("http", "proxy", proxy)
  77. if urlparse(proxy).scheme in HTTP_PROXY_SUPPORTED_SOCK_SCHEMAS:
  78. self.socks_proxy = proxy
  79. return config
  80. @contextmanager
  81. def fetch(self):
  82. from dulwich import porcelain
  83. local_path = tempfile.TemporaryDirectory()
  84. clone_args = {
  85. "branch": self.params.get('branch'),
  86. "config": self.config,
  87. "errstream": porcelain.NoneStream(),
  88. }
  89. # check if using socks for proxy - if so need to use custom pool_manager
  90. if self.socks_proxy:
  91. clone_args['pool_manager'] = ProxyPoolManager(self.socks_proxy)
  92. if self.url_scheme in ('http', 'https'):
  93. # Only pass explicit credentials if URL doesn't already contain embedded username
  94. # to avoid credential conflicts (see #20902)
  95. if not url_has_embedded_credentials(self.url) and self.params.get('username'):
  96. clone_args.update(
  97. {
  98. "username": self.params.get('username'),
  99. "password": self.params.get('password'),
  100. }
  101. )
  102. if self.url_scheme:
  103. clone_args["quiet"] = True
  104. clone_args["depth"] = 1
  105. logger.debug(f"Cloning git repo: {self.url}")
  106. try:
  107. porcelain.clone(self.url, local_path.name, **clone_args)
  108. except BaseException as e:
  109. raise SyncError(_("Fetching remote data failed ({name}): {error}").format(name=type(e).__name__, error=e))
  110. yield local_path.name
  111. local_path.cleanup()
  112. @register_data_backend()
  113. class S3Backend(DataBackend):
  114. name = 'amazon-s3'
  115. label = 'Amazon S3'
  116. parameters = {
  117. 'aws_access_key_id': forms.CharField(
  118. label=_('AWS access key ID'),
  119. widget=forms.TextInput(attrs={'class': 'form-control'})
  120. ),
  121. 'aws_secret_access_key': forms.CharField(
  122. label=_('AWS secret access key'),
  123. widget=forms.TextInput(attrs={'class': 'form-control'})
  124. ),
  125. }
  126. sensitive_parameters = ['aws_secret_access_key']
  127. REGION_REGEX = r's3\.([a-z0-9-]+)\.amazonaws\.com'
  128. def init_config(self):
  129. from botocore.config import Config as Boto3Config
  130. # Initialize backend config
  131. return Boto3Config(
  132. proxies=resolve_proxies(url=self.url, context={'client': self}),
  133. )
  134. @contextmanager
  135. def fetch(self):
  136. import boto3
  137. local_path = tempfile.TemporaryDirectory()
  138. local_root = Path(local_path.name).resolve()
  139. # Initialize the S3 resource and bucket
  140. aws_access_key_id = self.params.get('aws_access_key_id')
  141. aws_secret_access_key = self.params.get('aws_secret_access_key')
  142. s3 = boto3.resource(
  143. 's3',
  144. region_name=self._region_name,
  145. aws_access_key_id=aws_access_key_id,
  146. aws_secret_access_key=aws_secret_access_key,
  147. config=self.config,
  148. endpoint_url=self._endpoint_url
  149. )
  150. bucket = s3.Bucket(self._bucket_name)
  151. try:
  152. # Download all files within the specified path
  153. for obj in bucket.objects.filter(Prefix=self._remote_path):
  154. local_filename = self._resolve_local_path(local_root, obj.key)
  155. # Build local path
  156. local_filename.parent.mkdir(parents=True, exist_ok=True)
  157. bucket.download_file(obj.key, str(local_filename))
  158. yield local_path.name
  159. finally:
  160. local_path.cleanup()
  161. @staticmethod
  162. def _resolve_local_path(local_root, key):
  163. # S3 object keys are POSIX-style paths. Strip any leading separator so the key
  164. # joins onto the temp directory rather than replacing it, then ensure the
  165. # resolved destination remains within the temp directory to prevent path
  166. # traversal via crafted object keys.
  167. key_parts = PurePosixPath(key.lstrip('/')).parts
  168. local_filename = local_root.joinpath(*key_parts).resolve()
  169. if not local_filename.is_relative_to(local_root) or local_filename == local_root:
  170. raise SyncError(
  171. _("Invalid S3 object key '{key}': resolves outside of the local data directory").format(key=key)
  172. )
  173. return local_filename
  174. @property
  175. def _region_name(self):
  176. domain = urlparse(self.url).netloc
  177. if m := re.match(self.REGION_REGEX, domain):
  178. return m.group(1)
  179. return None
  180. @property
  181. def _bucket_name(self):
  182. url_path = urlparse(self.url).path.lstrip('/')
  183. return url_path.split('/')[0]
  184. @property
  185. def _endpoint_url(self):
  186. url_path = urlparse(self.url)
  187. return url_path._replace(params="", fragment="", query="", path="").geturl()
  188. @property
  189. def _remote_path(self):
  190. url_path = urlparse(self.url).path.lstrip('/')
  191. if '/' in url_path:
  192. return url_path.split('/', 1)[1]
  193. return ''