test_web.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. # test_web.py -- Tests for the git HTTP server
  2. # Copyright (C) 2010 Google, Inc.
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; version 2
  7. # or (at your option) any later version of the License.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  17. # MA 02110-1301, USA.
  18. """Tests for the Git HTTP server."""
  19. from io import BytesIO
  20. import gzip
  21. import re
  22. import os
  23. from dulwich.object_store import (
  24. MemoryObjectStore,
  25. )
  26. from dulwich.objects import (
  27. Blob,
  28. )
  29. from dulwich.repo import (
  30. BaseRepo,
  31. MemoryRepo,
  32. )
  33. from dulwich.server import (
  34. DictBackend,
  35. )
  36. from dulwich.tests import (
  37. TestCase,
  38. )
  39. from dulwich.web import (
  40. HTTP_OK,
  41. HTTP_NOT_FOUND,
  42. HTTP_FORBIDDEN,
  43. HTTP_ERROR,
  44. GunzipFilter,
  45. send_file,
  46. get_text_file,
  47. get_loose_object,
  48. get_pack_file,
  49. get_idx_file,
  50. get_info_refs,
  51. get_info_packs,
  52. handle_service_request,
  53. _LengthLimitedFile,
  54. HTTPGitRequest,
  55. HTTPGitApplication,
  56. )
  57. from dulwich.tests.utils import (
  58. make_object,
  59. make_tag,
  60. )
  61. class TestHTTPGitRequest(HTTPGitRequest):
  62. """HTTPGitRequest with overridden methods to help test caching."""
  63. def __init__(self, *args, **kwargs):
  64. HTTPGitRequest.__init__(self, *args, **kwargs)
  65. self.cached = None
  66. def nocache(self):
  67. self.cached = False
  68. def cache_forever(self):
  69. self.cached = True
  70. class WebTestCase(TestCase):
  71. """Base TestCase with useful instance vars and utility functions."""
  72. _req_class = TestHTTPGitRequest
  73. def setUp(self):
  74. super(WebTestCase, self).setUp()
  75. self._environ = {}
  76. self._req = self._req_class(self._environ, self._start_response,
  77. handlers=self._handlers())
  78. self._status = None
  79. self._headers = []
  80. self._output = BytesIO()
  81. def _start_response(self, status, headers):
  82. self._status = status
  83. self._headers = list(headers)
  84. return self._output.write
  85. def _handlers(self):
  86. return None
  87. def assertContentTypeEquals(self, expected):
  88. self.assertTrue(('Content-Type', expected) in self._headers)
  89. def _test_backend(objects, refs=None, named_files=None):
  90. if not refs:
  91. refs = {}
  92. if not named_files:
  93. named_files = {}
  94. repo = MemoryRepo.init_bare(objects, refs)
  95. for path, contents in named_files.items():
  96. repo._put_named_file(path, contents)
  97. return DictBackend({'/': repo})
  98. class DumbHandlersTestCase(WebTestCase):
  99. def test_send_file_not_found(self):
  100. list(send_file(self._req, None, 'text/plain'))
  101. self.assertEqual(HTTP_NOT_FOUND, self._status)
  102. def test_send_file(self):
  103. f = BytesIO(b'foobar')
  104. output = b''.join(send_file(self._req, f, 'some/thing'))
  105. self.assertEqual(b'foobar', output)
  106. self.assertEqual(HTTP_OK, self._status)
  107. self.assertContentTypeEquals('some/thing')
  108. self.assertTrue(f.closed)
  109. def test_send_file_buffered(self):
  110. bufsize = 10240
  111. xs = b'x' * bufsize
  112. f = BytesIO(2 * xs)
  113. self.assertEqual([xs, xs],
  114. list(send_file(self._req, f, 'some/thing')))
  115. self.assertEqual(HTTP_OK, self._status)
  116. self.assertContentTypeEquals('some/thing')
  117. self.assertTrue(f.closed)
  118. def test_send_file_error(self):
  119. class TestFile(object):
  120. def __init__(self, exc_class):
  121. self.closed = False
  122. self._exc_class = exc_class
  123. def read(self, size=-1):
  124. raise self._exc_class()
  125. def close(self):
  126. self.closed = True
  127. f = TestFile(IOError)
  128. list(send_file(self._req, f, 'some/thing'))
  129. self.assertEqual(HTTP_ERROR, self._status)
  130. self.assertTrue(f.closed)
  131. self.assertFalse(self._req.cached)
  132. # non-IOErrors are reraised
  133. f = TestFile(AttributeError)
  134. self.assertRaises(AttributeError, list,
  135. send_file(self._req, f, 'some/thing'))
  136. self.assertTrue(f.closed)
  137. self.assertFalse(self._req.cached)
  138. def test_get_text_file(self):
  139. backend = _test_backend([], named_files={'description': b'foo'})
  140. mat = re.search('.*', 'description')
  141. output = b''.join(get_text_file(self._req, backend, mat))
  142. self.assertEqual(b'foo', output)
  143. self.assertEqual(HTTP_OK, self._status)
  144. self.assertContentTypeEquals('text/plain')
  145. self.assertFalse(self._req.cached)
  146. def test_get_loose_object(self):
  147. blob = make_object(Blob, data=b'foo')
  148. backend = _test_backend([blob])
  149. mat = re.search('^(..)(.{38})$', blob.id.decode('ascii'))
  150. output = b''.join(get_loose_object(self._req, backend, mat))
  151. self.assertEqual(blob.as_legacy_object(), output)
  152. self.assertEqual(HTTP_OK, self._status)
  153. self.assertContentTypeEquals('application/x-git-loose-object')
  154. self.assertTrue(self._req.cached)
  155. def test_get_loose_object_missing(self):
  156. mat = re.search('^(..)(.{38})$', '1' * 40)
  157. list(get_loose_object(self._req, _test_backend([]), mat))
  158. self.assertEqual(HTTP_NOT_FOUND, self._status)
  159. def test_get_loose_object_error(self):
  160. blob = make_object(Blob, data=b'foo')
  161. backend = _test_backend([blob])
  162. mat = re.search('^(..)(.{38})$', blob.id.decode('ascii'))
  163. def as_legacy_object_error():
  164. raise IOError
  165. blob.as_legacy_object = as_legacy_object_error
  166. list(get_loose_object(self._req, backend, mat))
  167. self.assertEqual(HTTP_ERROR, self._status)
  168. def test_get_pack_file(self):
  169. pack_name = os.path.join('objects', 'pack', 'pack-%s.pack' % ('1' * 40))
  170. backend = _test_backend([], named_files={pack_name: b'pack contents'})
  171. mat = re.search('.*', pack_name)
  172. output = b''.join(get_pack_file(self._req, backend, mat))
  173. self.assertEqual(b'pack contents', output)
  174. self.assertEqual(HTTP_OK, self._status)
  175. self.assertContentTypeEquals('application/x-git-packed-objects')
  176. self.assertTrue(self._req.cached)
  177. def test_get_idx_file(self):
  178. idx_name = os.path.join('objects', 'pack', 'pack-%s.idx' % ('1' * 40))
  179. backend = _test_backend([], named_files={idx_name: b'idx contents'})
  180. mat = re.search('.*', idx_name)
  181. output = b''.join(get_idx_file(self._req, backend, mat))
  182. self.assertEqual(b'idx contents', output)
  183. self.assertEqual(HTTP_OK, self._status)
  184. self.assertContentTypeEquals('application/x-git-packed-objects-toc')
  185. self.assertTrue(self._req.cached)
  186. def test_get_info_refs(self):
  187. self._environ['QUERY_STRING'] = ''
  188. blob1 = make_object(Blob, data=b'1')
  189. blob2 = make_object(Blob, data=b'2')
  190. blob3 = make_object(Blob, data=b'3')
  191. tag1 = make_tag(blob2, name=b'tag-tag')
  192. objects = [blob1, blob2, blob3, tag1]
  193. refs = {
  194. b'HEAD': b'000',
  195. b'refs/heads/master': blob1.id,
  196. b'refs/tags/tag-tag': tag1.id,
  197. b'refs/tags/blob-tag': blob3.id,
  198. }
  199. backend = _test_backend(objects, refs=refs)
  200. mat = re.search('.*', '//info/refs')
  201. self.assertEqual([blob1.id + b'\trefs/heads/master\n',
  202. blob3.id + b'\trefs/tags/blob-tag\n',
  203. tag1.id + b'\trefs/tags/tag-tag\n',
  204. blob2.id + b'\trefs/tags/tag-tag^{}\n'],
  205. list(get_info_refs(self._req, backend, mat)))
  206. self.assertEqual(HTTP_OK, self._status)
  207. self.assertContentTypeEquals('text/plain')
  208. self.assertFalse(self._req.cached)
  209. def test_get_info_packs(self):
  210. class TestPackData(object):
  211. def __init__(self, sha):
  212. self.filename = "pack-%s.pack" % sha
  213. class TestPack(object):
  214. def __init__(self, sha):
  215. self.data = TestPackData(sha)
  216. packs = [TestPack(str(i) * 40) for i in range(1, 4)]
  217. class TestObjectStore(MemoryObjectStore):
  218. # property must be overridden, can't be assigned
  219. @property
  220. def packs(self):
  221. return packs
  222. store = TestObjectStore()
  223. repo = BaseRepo(store, None)
  224. backend = DictBackend({'/': repo})
  225. mat = re.search('.*', '//info/packs')
  226. output = b''.join(get_info_packs(self._req, backend, mat))
  227. expected = b''.join(
  228. [(b'P pack-' + s + b'.pack\n') for s in [b'1' * 40, b'2' * 40, b'3' * 40]])
  229. self.assertEqual(expected, output)
  230. self.assertEqual(HTTP_OK, self._status)
  231. self.assertContentTypeEquals('text/plain')
  232. self.assertFalse(self._req.cached)
  233. class SmartHandlersTestCase(WebTestCase):
  234. class _TestUploadPackHandler(object):
  235. def __init__(self, backend, args, proto, http_req=None,
  236. advertise_refs=False):
  237. self.args = args
  238. self.proto = proto
  239. self.http_req = http_req
  240. self.advertise_refs = advertise_refs
  241. def handle(self):
  242. self.proto.write(b'handled input: ' + self.proto.recv(1024))
  243. def _make_handler(self, *args, **kwargs):
  244. self._handler = self._TestUploadPackHandler(*args, **kwargs)
  245. return self._handler
  246. def _handlers(self):
  247. return {'git-upload-pack': self._make_handler}
  248. def test_handle_service_request_unknown(self):
  249. mat = re.search('.*', '/git-evil-handler')
  250. content = list(handle_service_request(self._req, 'backend', mat))
  251. self.assertEqual(HTTP_FORBIDDEN, self._status)
  252. self.assertFalse('git-evil-handler' in "".join(content))
  253. self.assertFalse(self._req.cached)
  254. def _run_handle_service_request(self, content_length=None):
  255. self._environ['wsgi.input'] = BytesIO(b'foo')
  256. if content_length is not None:
  257. self._environ['CONTENT_LENGTH'] = content_length
  258. mat = re.search('.*', '/git-upload-pack')
  259. handler_output = ''.join(
  260. handle_service_request(self._req, 'backend', mat))
  261. write_output = self._output.getvalue()
  262. # Ensure all output was written via the write callback.
  263. self.assertEqual('', handler_output)
  264. self.assertEqual(b'handled input: foo', write_output)
  265. self.assertContentTypeEquals('application/x-git-upload-pack-result')
  266. self.assertFalse(self._handler.advertise_refs)
  267. self.assertTrue(self._handler.http_req)
  268. self.assertFalse(self._req.cached)
  269. def test_handle_service_request(self):
  270. self._run_handle_service_request()
  271. def test_handle_service_request_with_length(self):
  272. self._run_handle_service_request(content_length='3')
  273. def test_handle_service_request_empty_length(self):
  274. self._run_handle_service_request(content_length='')
  275. def test_get_info_refs_unknown(self):
  276. self._environ['QUERY_STRING'] = 'service=git-evil-handler'
  277. content = list(get_info_refs(self._req, b'backend', None))
  278. self.assertFalse('git-evil-handler' in "".join(content))
  279. self.assertEqual(HTTP_FORBIDDEN, self._status)
  280. self.assertFalse(self._req.cached)
  281. def test_get_info_refs(self):
  282. self._environ['wsgi.input'] = BytesIO(b'foo')
  283. self._environ['QUERY_STRING'] = 'service=git-upload-pack'
  284. mat = re.search('.*', '/git-upload-pack')
  285. handler_output = b''.join(get_info_refs(self._req, b'backend', mat))
  286. write_output = self._output.getvalue()
  287. self.assertEqual((b'001e# service=git-upload-pack\n'
  288. b'0000'
  289. # input is ignored by the handler
  290. b'handled input: '), write_output)
  291. # Ensure all output was written via the write callback.
  292. self.assertEqual(b'', handler_output)
  293. self.assertTrue(self._handler.advertise_refs)
  294. self.assertTrue(self._handler.http_req)
  295. self.assertFalse(self._req.cached)
  296. class LengthLimitedFileTestCase(TestCase):
  297. def test_no_cutoff(self):
  298. f = _LengthLimitedFile(BytesIO(b'foobar'), 1024)
  299. self.assertEqual(b'foobar', f.read())
  300. def test_cutoff(self):
  301. f = _LengthLimitedFile(BytesIO(b'foobar'), 3)
  302. self.assertEqual(b'foo', f.read())
  303. self.assertEqual(b'', f.read())
  304. def test_multiple_reads(self):
  305. f = _LengthLimitedFile(BytesIO(b'foobar'), 3)
  306. self.assertEqual(b'fo', f.read(2))
  307. self.assertEqual(b'o', f.read(2))
  308. self.assertEqual(b'', f.read())
  309. class HTTPGitRequestTestCase(WebTestCase):
  310. # This class tests the contents of the actual cache headers
  311. _req_class = HTTPGitRequest
  312. def test_not_found(self):
  313. self._req.cache_forever() # cache headers should be discarded
  314. message = 'Something not found'
  315. self.assertEqual(message, self._req.not_found(message))
  316. self.assertEqual(HTTP_NOT_FOUND, self._status)
  317. self.assertEqual(set([('Content-Type', 'text/plain')]),
  318. set(self._headers))
  319. def test_forbidden(self):
  320. self._req.cache_forever() # cache headers should be discarded
  321. message = 'Something not found'
  322. self.assertEqual(message, self._req.forbidden(message))
  323. self.assertEqual(HTTP_FORBIDDEN, self._status)
  324. self.assertEqual(set([('Content-Type', 'text/plain')]),
  325. set(self._headers))
  326. def test_respond_ok(self):
  327. self._req.respond()
  328. self.assertEqual([], self._headers)
  329. self.assertEqual(HTTP_OK, self._status)
  330. def test_respond(self):
  331. self._req.nocache()
  332. self._req.respond(status=402, content_type='some/type',
  333. headers=[('X-Foo', 'foo'), ('X-Bar', 'bar')])
  334. self.assertEqual(set([
  335. ('X-Foo', 'foo'),
  336. ('X-Bar', 'bar'),
  337. ('Content-Type', 'some/type'),
  338. ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT'),
  339. ('Pragma', 'no-cache'),
  340. ('Cache-Control', 'no-cache, max-age=0, must-revalidate'),
  341. ]), set(self._headers))
  342. self.assertEqual(402, self._status)
  343. class HTTPGitApplicationTestCase(TestCase):
  344. def setUp(self):
  345. super(HTTPGitApplicationTestCase, self).setUp()
  346. self._app = HTTPGitApplication('backend')
  347. self._environ = {
  348. 'PATH_INFO': '/foo',
  349. 'REQUEST_METHOD': 'GET',
  350. }
  351. def _test_handler(self, req, backend, mat):
  352. # tests interface used by all handlers
  353. self.assertEqual(self._environ, req.environ)
  354. self.assertEqual('backend', backend)
  355. self.assertEqual('/foo', mat.group(0))
  356. return 'output'
  357. def _add_handler(self, app):
  358. req = self._environ['REQUEST_METHOD']
  359. app.services = {
  360. (req, re.compile('/foo$')): self._test_handler,
  361. }
  362. def test_call(self):
  363. self._add_handler(self._app)
  364. self.assertEqual('output', self._app(self._environ, None))
  365. def test_fallback_app(self):
  366. def test_app(environ, start_response):
  367. return 'output'
  368. app = HTTPGitApplication('backend', fallback_app=test_app)
  369. self.assertEqual('output', app(self._environ, None))
  370. class GunzipTestCase(HTTPGitApplicationTestCase):
  371. __doc__ = """TestCase for testing the GunzipFilter, ensuring the wsgi.input
  372. is correctly decompressed and headers are corrected.
  373. """
  374. example_text = __doc__.encode('ascii')
  375. def setUp(self):
  376. super(GunzipTestCase, self).setUp()
  377. self._app = GunzipFilter(self._app)
  378. self._environ['HTTP_CONTENT_ENCODING'] = 'gzip'
  379. self._environ['REQUEST_METHOD'] = 'POST'
  380. def _get_zstream(self, text):
  381. zstream = BytesIO()
  382. zfile = gzip.GzipFile(fileobj=zstream, mode='w')
  383. zfile.write(text)
  384. zfile.close()
  385. zlength = zstream.tell()
  386. zstream.seek(0)
  387. return zstream, zlength
  388. def _test_call(self, orig, zstream, zlength):
  389. self._add_handler(self._app.app)
  390. self.assertLess(zlength, len(orig))
  391. self.assertEqual(self._environ['HTTP_CONTENT_ENCODING'], 'gzip')
  392. self._environ['CONTENT_LENGTH'] = zlength
  393. self._environ['wsgi.input'] = zstream
  394. self._app(self._environ, None)
  395. buf = self._environ['wsgi.input']
  396. self.assertIsNot(buf, zstream)
  397. buf.seek(0)
  398. self.assertEqual(orig, buf.read())
  399. self.assertIs(None, self._environ.get('CONTENT_LENGTH'))
  400. self.assertNotIn('HTTP_CONTENT_ENCODING', self._environ)
  401. def test_call(self):
  402. self._test_call(
  403. self.example_text,
  404. *self._get_zstream(self.example_text)
  405. )
  406. def test_call_no_seek(self):
  407. """
  408. This ensures that the gunzipping code doesn't require any methods on
  409. 'wsgi.input' except for '.read()'. (In particular, it shouldn't
  410. require '.seek()'. See https://github.com/jelmer/dulwich/issues/140.)
  411. """
  412. class MinimalistWSGIInputStream(object):
  413. def __init__(self, data):
  414. self.data = data
  415. self.pos = 0
  416. def read(self, howmuch):
  417. start = self.pos
  418. end = self.pos + howmuch
  419. if start >= len(self.data):
  420. return ''
  421. self.pos = end
  422. return self.data[start:end]
  423. zstream, zlength = self._get_zstream(self.example_text)
  424. self._test_call(self.example_text,
  425. MinimalistWSGIInputStream(zstream.read()), zlength)