test_web.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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():
  182. raise IOError
  183. blob.as_legacy_object = as_legacy_object_error
  184. list(get_loose_object(self._req, backend, mat))
  185. self.assertEqual(HTTP_ERROR, self._status)
  186. def test_get_pack_file(self):
  187. pack_name = os.path.join('objects', 'pack', 'pack-%s.pack' % ('1' * 40))
  188. backend = _test_backend([], named_files={pack_name: b'pack contents'})
  189. mat = re.search('.*', pack_name)
  190. output = b''.join(get_pack_file(self._req, backend, mat))
  191. self.assertEqual(b'pack contents', output)
  192. self.assertEqual(HTTP_OK, self._status)
  193. self.assertContentTypeEquals('application/x-git-packed-objects')
  194. self.assertTrue(self._req.cached)
  195. def test_get_idx_file(self):
  196. idx_name = os.path.join('objects', 'pack', 'pack-%s.idx' % ('1' * 40))
  197. backend = _test_backend([], named_files={idx_name: b'idx contents'})
  198. mat = re.search('.*', idx_name)
  199. output = b''.join(get_idx_file(self._req, backend, mat))
  200. self.assertEqual(b'idx contents', output)
  201. self.assertEqual(HTTP_OK, self._status)
  202. self.assertContentTypeEquals('application/x-git-packed-objects-toc')
  203. self.assertTrue(self._req.cached)
  204. def test_get_info_refs(self):
  205. self._environ['QUERY_STRING'] = ''
  206. blob1 = make_object(Blob, data=b'1')
  207. blob2 = make_object(Blob, data=b'2')
  208. blob3 = make_object(Blob, data=b'3')
  209. tag1 = make_tag(blob2, name=b'tag-tag')
  210. objects = [blob1, blob2, blob3, tag1]
  211. refs = {
  212. b'HEAD': b'000',
  213. b'refs/heads/master': blob1.id,
  214. b'refs/tags/tag-tag': tag1.id,
  215. b'refs/tags/blob-tag': blob3.id,
  216. }
  217. backend = _test_backend(objects, refs=refs)
  218. mat = re.search('.*', '//info/refs')
  219. self.assertEqual([blob1.id + b'\trefs/heads/master\n',
  220. blob3.id + b'\trefs/tags/blob-tag\n',
  221. tag1.id + b'\trefs/tags/tag-tag\n',
  222. blob2.id + b'\trefs/tags/tag-tag^{}\n'],
  223. list(get_info_refs(self._req, backend, mat)))
  224. self.assertEqual(HTTP_OK, self._status)
  225. self.assertContentTypeEquals('text/plain')
  226. self.assertFalse(self._req.cached)
  227. def test_get_info_packs(self):
  228. class TestPackData(object):
  229. def __init__(self, sha):
  230. self.filename = "pack-%s.pack" % sha
  231. class TestPack(object):
  232. def __init__(self, sha):
  233. self.data = TestPackData(sha)
  234. packs = [TestPack(str(i) * 40) for i in range(1, 4)]
  235. class TestObjectStore(MemoryObjectStore):
  236. # property must be overridden, can't be assigned
  237. @property
  238. def packs(self):
  239. return packs
  240. store = TestObjectStore()
  241. repo = BaseRepo(store, None)
  242. backend = DictBackend({'/': repo})
  243. mat = re.search('.*', '//info/packs')
  244. output = b''.join(get_info_packs(self._req, backend, mat))
  245. expected = b''.join(
  246. [(b'P pack-' + s + b'.pack\n') for s in [b'1' * 40, b'2' * 40, b'3' * 40]])
  247. self.assertEqual(expected, output)
  248. self.assertEqual(HTTP_OK, self._status)
  249. self.assertContentTypeEquals('text/plain')
  250. self.assertFalse(self._req.cached)
  251. class SmartHandlersTestCase(WebTestCase):
  252. class _TestUploadPackHandler(object):
  253. def __init__(self, backend, args, proto, http_req=None,
  254. advertise_refs=False):
  255. self.args = args
  256. self.proto = proto
  257. self.http_req = http_req
  258. self.advertise_refs = advertise_refs
  259. def handle(self):
  260. self.proto.write(b'handled input: ' + self.proto.recv(1024))
  261. def _make_handler(self, *args, **kwargs):
  262. self._handler = self._TestUploadPackHandler(*args, **kwargs)
  263. return self._handler
  264. def _handlers(self):
  265. return {'git-upload-pack': self._make_handler}
  266. def test_handle_service_request_unknown(self):
  267. mat = re.search('.*', '/git-evil-handler')
  268. content = list(handle_service_request(self._req, 'backend', mat))
  269. self.assertEqual(HTTP_FORBIDDEN, self._status)
  270. self.assertFalse('git-evil-handler' in "".join(content))
  271. self.assertFalse(self._req.cached)
  272. def _run_handle_service_request(self, content_length=None):
  273. self._environ['wsgi.input'] = BytesIO(b'foo')
  274. if content_length is not None:
  275. self._environ['CONTENT_LENGTH'] = content_length
  276. mat = re.search('.*', '/git-upload-pack')
  277. handler_output = ''.join(
  278. handle_service_request(self._req, 'backend', mat))
  279. write_output = self._output.getvalue()
  280. # Ensure all output was written via the write callback.
  281. self.assertEqual('', handler_output)
  282. self.assertEqual(b'handled input: foo', write_output)
  283. self.assertContentTypeEquals('application/x-git-upload-pack-result')
  284. self.assertFalse(self._handler.advertise_refs)
  285. self.assertTrue(self._handler.http_req)
  286. self.assertFalse(self._req.cached)
  287. def test_handle_service_request(self):
  288. self._run_handle_service_request()
  289. def test_handle_service_request_with_length(self):
  290. self._run_handle_service_request(content_length='3')
  291. def test_handle_service_request_empty_length(self):
  292. self._run_handle_service_request(content_length='')
  293. def test_get_info_refs_unknown(self):
  294. self._environ['QUERY_STRING'] = 'service=git-evil-handler'
  295. content = list(get_info_refs(self._req, b'backend', None))
  296. self.assertFalse('git-evil-handler' in "".join(content))
  297. self.assertEqual(HTTP_FORBIDDEN, self._status)
  298. self.assertFalse(self._req.cached)
  299. def test_get_info_refs(self):
  300. self._environ['wsgi.input'] = BytesIO(b'foo')
  301. self._environ['QUERY_STRING'] = 'service=git-upload-pack'
  302. mat = re.search('.*', '/git-upload-pack')
  303. handler_output = b''.join(get_info_refs(self._req, b'backend', mat))
  304. write_output = self._output.getvalue()
  305. self.assertEqual((b'001e# service=git-upload-pack\n'
  306. b'0000'
  307. # input is ignored by the handler
  308. b'handled input: '), write_output)
  309. # Ensure all output was written via the write callback.
  310. self.assertEqual(b'', handler_output)
  311. self.assertTrue(self._handler.advertise_refs)
  312. self.assertTrue(self._handler.http_req)
  313. self.assertFalse(self._req.cached)
  314. class LengthLimitedFileTestCase(TestCase):
  315. def test_no_cutoff(self):
  316. f = _LengthLimitedFile(BytesIO(b'foobar'), 1024)
  317. self.assertEqual(b'foobar', f.read())
  318. def test_cutoff(self):
  319. f = _LengthLimitedFile(BytesIO(b'foobar'), 3)
  320. self.assertEqual(b'foo', f.read())
  321. self.assertEqual(b'', f.read())
  322. def test_multiple_reads(self):
  323. f = _LengthLimitedFile(BytesIO(b'foobar'), 3)
  324. self.assertEqual(b'fo', f.read(2))
  325. self.assertEqual(b'o', f.read(2))
  326. self.assertEqual(b'', f.read())
  327. class HTTPGitRequestTestCase(WebTestCase):
  328. # This class tests the contents of the actual cache headers
  329. _req_class = HTTPGitRequest
  330. def test_not_found(self):
  331. self._req.cache_forever() # cache headers should be discarded
  332. message = 'Something not found'
  333. self.assertEqual(message, self._req.not_found(message))
  334. self.assertEqual(HTTP_NOT_FOUND, self._status)
  335. self.assertEqual(set([('Content-Type', 'text/plain')]),
  336. set(self._headers))
  337. def test_forbidden(self):
  338. self._req.cache_forever() # cache headers should be discarded
  339. message = 'Something not found'
  340. self.assertEqual(message, self._req.forbidden(message))
  341. self.assertEqual(HTTP_FORBIDDEN, self._status)
  342. self.assertEqual(set([('Content-Type', 'text/plain')]),
  343. set(self._headers))
  344. def test_respond_ok(self):
  345. self._req.respond()
  346. self.assertEqual([], self._headers)
  347. self.assertEqual(HTTP_OK, self._status)
  348. def test_respond(self):
  349. self._req.nocache()
  350. self._req.respond(status=402, content_type='some/type',
  351. headers=[('X-Foo', 'foo'), ('X-Bar', 'bar')])
  352. self.assertEqual(set([
  353. ('X-Foo', 'foo'),
  354. ('X-Bar', 'bar'),
  355. ('Content-Type', 'some/type'),
  356. ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT'),
  357. ('Pragma', 'no-cache'),
  358. ('Cache-Control', 'no-cache, max-age=0, must-revalidate'),
  359. ]), set(self._headers))
  360. self.assertEqual(402, self._status)
  361. class HTTPGitApplicationTestCase(TestCase):
  362. def setUp(self):
  363. super(HTTPGitApplicationTestCase, self).setUp()
  364. self._app = HTTPGitApplication('backend')
  365. self._environ = {
  366. 'PATH_INFO': '/foo',
  367. 'REQUEST_METHOD': 'GET',
  368. }
  369. def _test_handler(self, req, backend, mat):
  370. # tests interface used by all handlers
  371. self.assertEqual(self._environ, req.environ)
  372. self.assertEqual('backend', backend)
  373. self.assertEqual('/foo', mat.group(0))
  374. return 'output'
  375. def _add_handler(self, app):
  376. req = self._environ['REQUEST_METHOD']
  377. app.services = {
  378. (req, re.compile('/foo$')): self._test_handler,
  379. }
  380. def test_call(self):
  381. self._add_handler(self._app)
  382. self.assertEqual('output', self._app(self._environ, None))
  383. def test_fallback_app(self):
  384. def test_app(environ, start_response):
  385. return 'output'
  386. app = HTTPGitApplication('backend', fallback_app=test_app)
  387. self.assertEqual('output', app(self._environ, None))
  388. class GunzipTestCase(HTTPGitApplicationTestCase):
  389. __doc__ = """TestCase for testing the GunzipFilter, ensuring the wsgi.input
  390. is correctly decompressed and headers are corrected.
  391. """
  392. example_text = __doc__.encode('ascii')
  393. def setUp(self):
  394. super(GunzipTestCase, self).setUp()
  395. self._app = GunzipFilter(self._app)
  396. self._environ['HTTP_CONTENT_ENCODING'] = 'gzip'
  397. self._environ['REQUEST_METHOD'] = 'POST'
  398. def _get_zstream(self, text):
  399. zstream = BytesIO()
  400. zfile = gzip.GzipFile(fileobj=zstream, mode='w')
  401. zfile.write(text)
  402. zfile.close()
  403. zlength = zstream.tell()
  404. zstream.seek(0)
  405. return zstream, zlength
  406. def _test_call(self, orig, zstream, zlength):
  407. self._add_handler(self._app.app)
  408. self.assertLess(zlength, len(orig))
  409. self.assertEqual(self._environ['HTTP_CONTENT_ENCODING'], 'gzip')
  410. self._environ['CONTENT_LENGTH'] = zlength
  411. self._environ['wsgi.input'] = zstream
  412. self._app(self._environ, None)
  413. buf = self._environ['wsgi.input']
  414. self.assertIsNot(buf, zstream)
  415. buf.seek(0)
  416. self.assertEqual(orig, buf.read())
  417. self.assertIs(None, self._environ.get('CONTENT_LENGTH'))
  418. self.assertNotIn('HTTP_CONTENT_ENCODING', self._environ)
  419. def test_call(self):
  420. self._test_call(
  421. self.example_text,
  422. *self._get_zstream(self.example_text)
  423. )
  424. def test_call_no_seek(self):
  425. """
  426. This ensures that the gunzipping code doesn't require any methods on
  427. 'wsgi.input' except for '.read()'. (In particular, it shouldn't
  428. require '.seek()'. See https://github.com/jelmer/dulwich/issues/140.)
  429. """
  430. zstream, zlength = self._get_zstream(self.example_text)
  431. self._test_call(self.example_text,
  432. MinimalistWSGIInputStream(zstream.read()), zlength)
  433. def test_call_no_working_seek(self):
  434. """
  435. Similar to 'test_call_no_seek', but this time the methods are available
  436. (but defunct). See https://github.com/jonashaag/klaus/issues/154.
  437. """
  438. zstream, zlength = self._get_zstream(self.example_text)
  439. self._test_call(self.example_text,
  440. MinimalistWSGIInputStream2(zstream.read()), zlength)