test_web.py 19 KB

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