test_web.py 19 KB

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