test_data_backends.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. import tempfile
  2. from datetime import UTC, datetime
  3. from pathlib import Path
  4. from unittest import skipIf
  5. from unittest.mock import patch
  6. from django.test import TestCase
  7. from core.data_backends import S3Backend, url_has_embedded_credentials
  8. from core.exceptions import SyncError
  9. try:
  10. import dulwich # noqa: F401
  11. DULWICH_AVAILABLE = True
  12. except ImportError:
  13. DULWICH_AVAILABLE = False
  14. class URLEmbeddedCredentialsTestCase(TestCase):
  15. def test_url_with_embedded_username(self):
  16. self.assertTrue(url_has_embedded_credentials('https://myuser@bitbucket.org/workspace/repo.git'))
  17. def test_url_without_embedded_username(self):
  18. self.assertFalse(url_has_embedded_credentials('https://bitbucket.org/workspace/repo.git'))
  19. def test_url_with_username_and_password(self):
  20. self.assertTrue(url_has_embedded_credentials('https://user:pass@bitbucket.org/workspace/repo.git'))
  21. def test_various_providers_with_embedded_username(self):
  22. urls = [
  23. 'https://user@bitbucket.org/workspace/repo.git',
  24. 'https://user@github.com/owner/repo.git',
  25. 'https://deploy-key@gitlab.com/group/project.git',
  26. 'http://user@internal-git.example.com/repo.git',
  27. ]
  28. for url in urls:
  29. with self.subTest(url=url):
  30. self.assertTrue(url_has_embedded_credentials(url))
  31. def test_various_providers_without_embedded_username(self):
  32. """Various Git providers without embedded usernames."""
  33. urls = [
  34. 'https://bitbucket.org/workspace/repo.git',
  35. 'https://github.com/owner/repo.git',
  36. 'https://gitlab.com/group/project.git',
  37. 'http://internal-git.example.com/repo.git',
  38. ]
  39. for url in urls:
  40. with self.subTest(url=url):
  41. self.assertFalse(url_has_embedded_credentials(url))
  42. def test_ssh_url(self):
  43. # git@host:path format doesn't parse as having a username in the traditional sense
  44. self.assertFalse(url_has_embedded_credentials('git@github.com:owner/repo.git'))
  45. def test_file_url(self):
  46. self.assertFalse(url_has_embedded_credentials('file:///path/to/repo'))
  47. @skipIf(not DULWICH_AVAILABLE, "dulwich is not installed")
  48. class GitBackendCredentialIntegrationTestCase(TestCase):
  49. """
  50. Integration tests that verify GitBackend correctly applies credential logic.
  51. These tests require dulwich to be installed and verify the full integration
  52. of the credential handling in GitBackend.fetch().
  53. """
  54. def _get_clone_kwargs(self, url, **params):
  55. from core.data_backends import GitBackend
  56. backend = GitBackend(url=url, **params)
  57. with patch('dulwich.porcelain.clone') as mock_clone, \
  58. patch('dulwich.porcelain.NoneStream'):
  59. try:
  60. with backend.fetch():
  61. pass
  62. except Exception:
  63. pass
  64. if mock_clone.called:
  65. return mock_clone.call_args.kwargs
  66. return {}
  67. def test_url_with_embedded_username_skips_explicit_credentials(self):
  68. kwargs = self._get_clone_kwargs(
  69. url='https://myuser@bitbucket.org/workspace/repo.git',
  70. username='myuser',
  71. password='my-api-key'
  72. )
  73. self.assertEqual(kwargs.get('username'), None)
  74. self.assertEqual(kwargs.get('password'), None)
  75. def test_url_without_embedded_username_passes_explicit_credentials(self):
  76. kwargs = self._get_clone_kwargs(
  77. url='https://bitbucket.org/workspace/repo.git',
  78. username='myuser',
  79. password='my-api-key'
  80. )
  81. self.assertEqual(kwargs.get('username'), 'myuser')
  82. self.assertEqual(kwargs.get('password'), 'my-api-key')
  83. def test_url_with_embedded_username_no_explicit_credentials(self):
  84. kwargs = self._get_clone_kwargs(
  85. url='https://myuser@bitbucket.org/workspace/repo.git'
  86. )
  87. self.assertEqual(kwargs.get('username'), None)
  88. self.assertEqual(kwargs.get('password'), None)
  89. def test_public_repo_no_credentials(self):
  90. kwargs = self._get_clone_kwargs(
  91. url='https://github.com/public/repo.git'
  92. )
  93. self.assertEqual(kwargs.get('username'), None)
  94. self.assertEqual(kwargs.get('password'), None)
  95. @skipIf(not DULWICH_AVAILABLE, "dulwich is not installed")
  96. class GitBackendRevisionTestCase(TestCase):
  97. def setUp(self):
  98. from dulwich import porcelain
  99. temp_dir = tempfile.TemporaryDirectory()
  100. self.addCleanup(temp_dir.cleanup)
  101. self.repo_path = Path(temp_dir.name)
  102. porcelain.init(str(self.repo_path))
  103. for content, message in (('one\n', b'First commit'), ('two\n', b'Second commit\n\nAdd more detail\n')):
  104. (self.repo_path / 'file.txt').write_text(content)
  105. porcelain.add(str(self.repo_path), [str(self.repo_path / 'file.txt')])
  106. self.commit = porcelain.commit(
  107. str(self.repo_path),
  108. message=message,
  109. author=b'Jane Doe <jane@example.com>',
  110. committer=b'John Doe <john@example.com>',
  111. author_timestamp=1600000000,
  112. author_timezone=3600,
  113. commit_timestamp=1700000000,
  114. commit_timezone=3600,
  115. )
  116. def test_get_revision(self):
  117. """The revision describes the head commit of the fetched clone, as of its authoring."""
  118. from core.data_backends import GitBackend
  119. backend = GitBackend(url=self.repo_path.as_uri())
  120. with backend.fetch() as local_path:
  121. revision = backend.get_revision(local_path)
  122. self.assertEqual(revision, {
  123. 'revision': self.commit.decode(),
  124. 'message': 'Second commit\n\nAdd more detail',
  125. 'author': 'Jane Doe <jane@example.com>',
  126. 'time': datetime(2020, 9, 13, 12, 26, 40, tzinfo=UTC),
  127. })
  128. class S3BackendKeyResolutionTestCase(TestCase):
  129. """
  130. Verify that S3Backend resolves object keys to local paths safely, rejecting any
  131. key that would write outside of the local temporary directory.
  132. """
  133. def setUp(self):
  134. self._tmp = tempfile.TemporaryDirectory()
  135. self.addCleanup(self._tmp.cleanup)
  136. self.local_root = Path(self._tmp.name).resolve()
  137. def test_simple_key_resolves_under_root(self):
  138. result = S3Backend._resolve_local_path(self.local_root, 'data/file.yaml')
  139. self.assertEqual(result, self.local_root / 'data' / 'file.yaml')
  140. def test_nested_key_resolves_under_root(self):
  141. result = S3Backend._resolve_local_path(self.local_root, 'a/b/c/d.txt')
  142. self.assertEqual(result, self.local_root / 'a' / 'b' / 'c' / 'd.txt')
  143. def test_absolute_key_is_contained(self):
  144. # A key beginning with '/' must not escape the local root
  145. result = S3Backend._resolve_local_path(self.local_root, '/etc/passwd')
  146. self.assertEqual(result, self.local_root / 'etc' / 'passwd')
  147. self.assertTrue(result.is_relative_to(self.local_root))
  148. def test_parent_traversal_is_rejected(self):
  149. with self.assertRaises(SyncError):
  150. S3Backend._resolve_local_path(self.local_root, '../escape.txt')
  151. def test_nested_parent_traversal_is_rejected(self):
  152. with self.assertRaises(SyncError):
  153. S3Backend._resolve_local_path(self.local_root, 'foo/../../escape.txt')
  154. def test_absolute_parent_traversal_is_rejected(self):
  155. with self.assertRaises(SyncError):
  156. S3Backend._resolve_local_path(self.local_root, '/../escape.txt')
  157. def test_empty_key_is_rejected(self):
  158. with self.assertRaises(SyncError):
  159. S3Backend._resolve_local_path(self.local_root, '')
  160. def test_root_key_is_rejected(self):
  161. with self.assertRaises(SyncError):
  162. S3Backend._resolve_local_path(self.local_root, '/')