test_web.py 20 KB

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