test_web.py 19 KB

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