1
0

test_url_preview.py 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  1. # Copyright 2018 New Vector Ltd
  2. # Copyright 2021 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import base64
  16. import json
  17. import os
  18. import re
  19. from typing import Any, Dict, Optional, Sequence, Tuple, Type
  20. from urllib.parse import quote, urlencode
  21. from twisted.internet._resolver import HostResolution
  22. from twisted.internet.address import IPv4Address, IPv6Address
  23. from twisted.internet.error import DNSLookupError
  24. from twisted.internet.interfaces import IAddress, IResolutionReceiver
  25. from twisted.test.proto_helpers import AccumulatingProtocol, MemoryReactor
  26. from synapse.config.oembed import OEmbedEndpointConfig
  27. from synapse.rest.media.v1.media_repository import MediaRepositoryResource
  28. from synapse.rest.media.v1.preview_url_resource import IMAGE_CACHE_EXPIRY_MS
  29. from synapse.server import HomeServer
  30. from synapse.types import JsonDict
  31. from synapse.util import Clock
  32. from synapse.util.stringutils import parse_and_validate_mxc_uri
  33. from tests import unittest
  34. from tests.server import FakeTransport
  35. from tests.test_utils import SMALL_PNG
  36. from tests.utils import MockClock
  37. try:
  38. import lxml
  39. except ImportError:
  40. lxml = None
  41. class URLPreviewTests(unittest.HomeserverTestCase):
  42. if not lxml:
  43. skip = "url preview feature requires lxml"
  44. hijack_auth = True
  45. user_id = "@test:user"
  46. end_content = (
  47. b"<html><head>"
  48. b'<meta property="og:title" content="~matrix~" />'
  49. b'<meta property="og:description" content="hi" />'
  50. b"</head></html>"
  51. )
  52. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  53. config = self.default_config()
  54. config["url_preview_enabled"] = True
  55. config["max_spider_size"] = 9999999
  56. config["url_preview_ip_range_blacklist"] = (
  57. "192.168.1.1",
  58. "1.0.0.0/8",
  59. "3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
  60. "2001:800::/21",
  61. )
  62. config["url_preview_ip_range_whitelist"] = ("1.1.1.1",)
  63. config["url_preview_accept_language"] = [
  64. "en-UK",
  65. "en-US;q=0.9",
  66. "fr;q=0.8",
  67. "*;q=0.7",
  68. ]
  69. self.storage_path = self.mktemp()
  70. self.media_store_path = self.mktemp()
  71. os.mkdir(self.storage_path)
  72. os.mkdir(self.media_store_path)
  73. config["media_store_path"] = self.media_store_path
  74. provider_config = {
  75. "module": "synapse.rest.media.v1.storage_provider.FileStorageProviderBackend",
  76. "store_local": True,
  77. "store_synchronous": False,
  78. "store_remote": True,
  79. "config": {"directory": self.storage_path},
  80. }
  81. config["media_storage_providers"] = [provider_config]
  82. hs = self.setup_test_homeserver(config=config)
  83. # After the hs is created, modify the parsed oEmbed config (to avoid
  84. # messing with files).
  85. #
  86. # Note that HTTP URLs are used to avoid having to deal with TLS in tests.
  87. hs.config.oembed.oembed_patterns = [
  88. OEmbedEndpointConfig(
  89. api_endpoint="http://publish.twitter.com/oembed",
  90. url_patterns=[
  91. re.compile(r"http://twitter\.com/.+/status/.+"),
  92. ],
  93. formats=None,
  94. ),
  95. OEmbedEndpointConfig(
  96. api_endpoint="http://www.hulu.com/api/oembed.{format}",
  97. url_patterns=[
  98. re.compile(r"http://www\.hulu\.com/watch/.+"),
  99. ],
  100. formats=["json"],
  101. ),
  102. ]
  103. return hs
  104. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  105. self.media_repo = hs.get_media_repository_resource()
  106. self.preview_url = self.media_repo.children[b"preview_url"]
  107. self.lookups: Dict[str, Any] = {}
  108. class Resolver:
  109. def resolveHostName(
  110. _self,
  111. resolutionReceiver: IResolutionReceiver,
  112. hostName: str,
  113. portNumber: int = 0,
  114. addressTypes: Optional[Sequence[Type[IAddress]]] = None,
  115. transportSemantics: str = "TCP",
  116. ) -> IResolutionReceiver:
  117. resolution = HostResolution(hostName)
  118. resolutionReceiver.resolutionBegan(resolution)
  119. if hostName not in self.lookups:
  120. raise DNSLookupError("OH NO")
  121. for i in self.lookups[hostName]:
  122. resolutionReceiver.addressResolved(i[0]("TCP", i[1], portNumber))
  123. resolutionReceiver.resolutionComplete()
  124. return resolutionReceiver
  125. self.reactor.nameResolver = Resolver() # type: ignore[assignment]
  126. def create_test_resource(self) -> MediaRepositoryResource:
  127. return self.hs.get_media_repository_resource()
  128. def _assert_small_png(self, json_body: JsonDict) -> None:
  129. """Assert properties from the SMALL_PNG test image."""
  130. self.assertTrue(json_body["og:image"].startswith("mxc://"))
  131. self.assertEqual(json_body["og:image:height"], 1)
  132. self.assertEqual(json_body["og:image:width"], 1)
  133. self.assertEqual(json_body["og:image:type"], "image/png")
  134. self.assertEqual(json_body["matrix:image:size"], 67)
  135. def test_cache_returns_correct_type(self) -> None:
  136. self.lookups["matrix.org"] = [(IPv4Address, "10.1.2.3")]
  137. channel = self.make_request(
  138. "GET",
  139. "preview_url?url=http://matrix.org",
  140. shorthand=False,
  141. await_result=False,
  142. )
  143. self.pump()
  144. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  145. server = AccumulatingProtocol()
  146. server.makeConnection(FakeTransport(client, self.reactor))
  147. client.makeConnection(FakeTransport(server, self.reactor))
  148. client.dataReceived(
  149. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\nContent-Type: text/html\r\n\r\n"
  150. % (len(self.end_content),)
  151. + self.end_content
  152. )
  153. self.pump()
  154. self.assertEqual(channel.code, 200)
  155. self.assertEqual(
  156. channel.json_body, {"og:title": "~matrix~", "og:description": "hi"}
  157. )
  158. # Check the cache returns the correct response
  159. channel = self.make_request(
  160. "GET", "preview_url?url=http://matrix.org", shorthand=False
  161. )
  162. # Check the cache response has the same content
  163. self.assertEqual(channel.code, 200)
  164. self.assertEqual(
  165. channel.json_body, {"og:title": "~matrix~", "og:description": "hi"}
  166. )
  167. # Clear the in-memory cache
  168. self.assertIn("http://matrix.org", self.preview_url._cache)
  169. self.preview_url._cache.pop("http://matrix.org")
  170. self.assertNotIn("http://matrix.org", self.preview_url._cache)
  171. # Check the database cache returns the correct response
  172. channel = self.make_request(
  173. "GET", "preview_url?url=http://matrix.org", shorthand=False
  174. )
  175. # Check the cache response has the same content
  176. self.assertEqual(channel.code, 200)
  177. self.assertEqual(
  178. channel.json_body, {"og:title": "~matrix~", "og:description": "hi"}
  179. )
  180. def test_non_ascii_preview_httpequiv(self) -> None:
  181. self.lookups["matrix.org"] = [(IPv4Address, "10.1.2.3")]
  182. end_content = (
  183. b"<html><head>"
  184. b'<meta http-equiv="Content-Type" content="text/html; charset=windows-1251"/>'
  185. b'<meta property="og:title" content="\xe4\xea\xe0" />'
  186. b'<meta property="og:description" content="hi" />'
  187. b"</head></html>"
  188. )
  189. channel = self.make_request(
  190. "GET",
  191. "preview_url?url=http://matrix.org",
  192. shorthand=False,
  193. await_result=False,
  194. )
  195. self.pump()
  196. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  197. server = AccumulatingProtocol()
  198. server.makeConnection(FakeTransport(client, self.reactor))
  199. client.makeConnection(FakeTransport(server, self.reactor))
  200. client.dataReceived(
  201. (
  202. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  203. b'Content-Type: text/html; charset="utf8"\r\n\r\n'
  204. )
  205. % (len(end_content),)
  206. + end_content
  207. )
  208. self.pump()
  209. self.assertEqual(channel.code, 200)
  210. self.assertEqual(channel.json_body["og:title"], "\u0434\u043a\u0430")
  211. def test_video_rejected(self) -> None:
  212. self.lookups["matrix.org"] = [(IPv4Address, "10.1.2.3")]
  213. end_content = b"anything"
  214. channel = self.make_request(
  215. "GET",
  216. "preview_url?url=http://matrix.org",
  217. shorthand=False,
  218. await_result=False,
  219. )
  220. self.pump()
  221. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  222. server = AccumulatingProtocol()
  223. server.makeConnection(FakeTransport(client, self.reactor))
  224. client.makeConnection(FakeTransport(server, self.reactor))
  225. client.dataReceived(
  226. (
  227. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  228. b"Content-Type: video/mp4\r\n\r\n"
  229. )
  230. % (len(end_content))
  231. + end_content
  232. )
  233. self.pump()
  234. self.assertEqual(channel.code, 502)
  235. self.assertEqual(
  236. channel.json_body,
  237. {
  238. "errcode": "M_UNKNOWN",
  239. "error": "Requested file's content type not allowed for this operation: video/mp4",
  240. },
  241. )
  242. def test_audio_rejected(self) -> None:
  243. self.lookups["matrix.org"] = [(IPv4Address, "10.1.2.3")]
  244. end_content = b"anything"
  245. channel = self.make_request(
  246. "GET",
  247. "preview_url?url=http://matrix.org",
  248. shorthand=False,
  249. await_result=False,
  250. )
  251. self.pump()
  252. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  253. server = AccumulatingProtocol()
  254. server.makeConnection(FakeTransport(client, self.reactor))
  255. client.makeConnection(FakeTransport(server, self.reactor))
  256. client.dataReceived(
  257. (
  258. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  259. b"Content-Type: audio/aac\r\n\r\n"
  260. )
  261. % (len(end_content))
  262. + end_content
  263. )
  264. self.pump()
  265. self.assertEqual(channel.code, 502)
  266. self.assertEqual(
  267. channel.json_body,
  268. {
  269. "errcode": "M_UNKNOWN",
  270. "error": "Requested file's content type not allowed for this operation: audio/aac",
  271. },
  272. )
  273. def test_non_ascii_preview_content_type(self) -> None:
  274. self.lookups["matrix.org"] = [(IPv4Address, "10.1.2.3")]
  275. end_content = (
  276. b"<html><head>"
  277. b'<meta property="og:title" content="\xe4\xea\xe0" />'
  278. b'<meta property="og:description" content="hi" />'
  279. b"</head></html>"
  280. )
  281. channel = self.make_request(
  282. "GET",
  283. "preview_url?url=http://matrix.org",
  284. shorthand=False,
  285. await_result=False,
  286. )
  287. self.pump()
  288. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  289. server = AccumulatingProtocol()
  290. server.makeConnection(FakeTransport(client, self.reactor))
  291. client.makeConnection(FakeTransport(server, self.reactor))
  292. client.dataReceived(
  293. (
  294. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  295. b'Content-Type: text/html; charset="windows-1251"\r\n\r\n'
  296. )
  297. % (len(end_content),)
  298. + end_content
  299. )
  300. self.pump()
  301. self.assertEqual(channel.code, 200)
  302. self.assertEqual(channel.json_body["og:title"], "\u0434\u043a\u0430")
  303. def test_overlong_title(self) -> None:
  304. self.lookups["matrix.org"] = [(IPv4Address, "10.1.2.3")]
  305. end_content = (
  306. b"<html><head>"
  307. b"<title>" + b"x" * 2000 + b"</title>"
  308. b'<meta property="og:description" content="hi" />'
  309. b"</head></html>"
  310. )
  311. channel = self.make_request(
  312. "GET",
  313. "preview_url?url=http://matrix.org",
  314. shorthand=False,
  315. await_result=False,
  316. )
  317. self.pump()
  318. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  319. server = AccumulatingProtocol()
  320. server.makeConnection(FakeTransport(client, self.reactor))
  321. client.makeConnection(FakeTransport(server, self.reactor))
  322. client.dataReceived(
  323. (
  324. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  325. b'Content-Type: text/html; charset="windows-1251"\r\n\r\n'
  326. )
  327. % (len(end_content),)
  328. + end_content
  329. )
  330. self.pump()
  331. self.assertEqual(channel.code, 200)
  332. res = channel.json_body
  333. # We should only see the `og:description` field, as `title` is too long and should be stripped out
  334. self.assertCountEqual(["og:description"], res.keys())
  335. def test_ipaddr(self) -> None:
  336. """
  337. IP addresses can be previewed directly.
  338. """
  339. self.lookups["example.com"] = [(IPv4Address, "10.1.2.3")]
  340. channel = self.make_request(
  341. "GET",
  342. "preview_url?url=http://example.com",
  343. shorthand=False,
  344. await_result=False,
  345. )
  346. self.pump()
  347. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  348. server = AccumulatingProtocol()
  349. server.makeConnection(FakeTransport(client, self.reactor))
  350. client.makeConnection(FakeTransport(server, self.reactor))
  351. client.dataReceived(
  352. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\nContent-Type: text/html\r\n\r\n"
  353. % (len(self.end_content),)
  354. + self.end_content
  355. )
  356. self.pump()
  357. self.assertEqual(channel.code, 200)
  358. self.assertEqual(
  359. channel.json_body, {"og:title": "~matrix~", "og:description": "hi"}
  360. )
  361. def test_blacklisted_ip_specific(self) -> None:
  362. """
  363. Blacklisted IP addresses, found via DNS, are not spidered.
  364. """
  365. self.lookups["example.com"] = [(IPv4Address, "192.168.1.1")]
  366. channel = self.make_request(
  367. "GET", "preview_url?url=http://example.com", shorthand=False
  368. )
  369. # No requests made.
  370. self.assertEqual(len(self.reactor.tcpClients), 0)
  371. self.assertEqual(channel.code, 502)
  372. self.assertEqual(
  373. channel.json_body,
  374. {
  375. "errcode": "M_UNKNOWN",
  376. "error": "DNS resolution failure during URL preview generation",
  377. },
  378. )
  379. def test_blacklisted_ip_range(self) -> None:
  380. """
  381. Blacklisted IP ranges, IPs found over DNS, are not spidered.
  382. """
  383. self.lookups["example.com"] = [(IPv4Address, "1.1.1.2")]
  384. channel = self.make_request(
  385. "GET", "preview_url?url=http://example.com", shorthand=False
  386. )
  387. self.assertEqual(channel.code, 502)
  388. self.assertEqual(
  389. channel.json_body,
  390. {
  391. "errcode": "M_UNKNOWN",
  392. "error": "DNS resolution failure during URL preview generation",
  393. },
  394. )
  395. def test_blacklisted_ip_specific_direct(self) -> None:
  396. """
  397. Blacklisted IP addresses, accessed directly, are not spidered.
  398. """
  399. channel = self.make_request(
  400. "GET", "preview_url?url=http://192.168.1.1", shorthand=False
  401. )
  402. # No requests made.
  403. self.assertEqual(len(self.reactor.tcpClients), 0)
  404. self.assertEqual(
  405. channel.json_body,
  406. {
  407. "errcode": "M_UNKNOWN",
  408. "error": "IP address blocked by IP blacklist entry",
  409. },
  410. )
  411. self.assertEqual(channel.code, 403)
  412. def test_blacklisted_ip_range_direct(self) -> None:
  413. """
  414. Blacklisted IP ranges, accessed directly, are not spidered.
  415. """
  416. channel = self.make_request(
  417. "GET", "preview_url?url=http://1.1.1.2", shorthand=False
  418. )
  419. self.assertEqual(channel.code, 403)
  420. self.assertEqual(
  421. channel.json_body,
  422. {
  423. "errcode": "M_UNKNOWN",
  424. "error": "IP address blocked by IP blacklist entry",
  425. },
  426. )
  427. def test_blacklisted_ip_range_whitelisted_ip(self) -> None:
  428. """
  429. Blacklisted but then subsequently whitelisted IP addresses can be
  430. spidered.
  431. """
  432. self.lookups["example.com"] = [(IPv4Address, "1.1.1.1")]
  433. channel = self.make_request(
  434. "GET",
  435. "preview_url?url=http://example.com",
  436. shorthand=False,
  437. await_result=False,
  438. )
  439. self.pump()
  440. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  441. server = AccumulatingProtocol()
  442. server.makeConnection(FakeTransport(client, self.reactor))
  443. client.makeConnection(FakeTransport(server, self.reactor))
  444. client.dataReceived(
  445. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\nContent-Type: text/html\r\n\r\n"
  446. % (len(self.end_content),)
  447. + self.end_content
  448. )
  449. self.pump()
  450. self.assertEqual(channel.code, 200)
  451. self.assertEqual(
  452. channel.json_body, {"og:title": "~matrix~", "og:description": "hi"}
  453. )
  454. def test_blacklisted_ip_with_external_ip(self) -> None:
  455. """
  456. If a hostname resolves a blacklisted IP, even if there's a
  457. non-blacklisted one, it will be rejected.
  458. """
  459. # Hardcode the URL resolving to the IP we want.
  460. self.lookups["example.com"] = [
  461. (IPv4Address, "1.1.1.2"),
  462. (IPv4Address, "10.1.2.3"),
  463. ]
  464. channel = self.make_request(
  465. "GET", "preview_url?url=http://example.com", shorthand=False
  466. )
  467. self.assertEqual(channel.code, 502)
  468. self.assertEqual(
  469. channel.json_body,
  470. {
  471. "errcode": "M_UNKNOWN",
  472. "error": "DNS resolution failure during URL preview generation",
  473. },
  474. )
  475. def test_blacklisted_ipv6_specific(self) -> None:
  476. """
  477. Blacklisted IP addresses, found via DNS, are not spidered.
  478. """
  479. self.lookups["example.com"] = [
  480. (IPv6Address, "3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")
  481. ]
  482. channel = self.make_request(
  483. "GET", "preview_url?url=http://example.com", shorthand=False
  484. )
  485. # No requests made.
  486. self.assertEqual(len(self.reactor.tcpClients), 0)
  487. self.assertEqual(channel.code, 502)
  488. self.assertEqual(
  489. channel.json_body,
  490. {
  491. "errcode": "M_UNKNOWN",
  492. "error": "DNS resolution failure during URL preview generation",
  493. },
  494. )
  495. def test_blacklisted_ipv6_range(self) -> None:
  496. """
  497. Blacklisted IP ranges, IPs found over DNS, are not spidered.
  498. """
  499. self.lookups["example.com"] = [(IPv6Address, "2001:800::1")]
  500. channel = self.make_request(
  501. "GET", "preview_url?url=http://example.com", shorthand=False
  502. )
  503. self.assertEqual(channel.code, 502)
  504. self.assertEqual(
  505. channel.json_body,
  506. {
  507. "errcode": "M_UNKNOWN",
  508. "error": "DNS resolution failure during URL preview generation",
  509. },
  510. )
  511. def test_OPTIONS(self) -> None:
  512. """
  513. OPTIONS returns the OPTIONS.
  514. """
  515. channel = self.make_request(
  516. "OPTIONS", "preview_url?url=http://example.com", shorthand=False
  517. )
  518. self.assertEqual(channel.code, 200)
  519. self.assertEqual(channel.json_body, {})
  520. def test_accept_language_config_option(self) -> None:
  521. """
  522. Accept-Language header is sent to the remote server
  523. """
  524. self.lookups["example.com"] = [(IPv4Address, "10.1.2.3")]
  525. # Build and make a request to the server
  526. channel = self.make_request(
  527. "GET",
  528. "preview_url?url=http://example.com",
  529. shorthand=False,
  530. await_result=False,
  531. )
  532. self.pump()
  533. # Extract Synapse's tcp client
  534. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  535. # Build a fake remote server to reply with
  536. server = AccumulatingProtocol()
  537. # Connect the two together
  538. server.makeConnection(FakeTransport(client, self.reactor))
  539. client.makeConnection(FakeTransport(server, self.reactor))
  540. # Tell Synapse that it has received some data from the remote server
  541. client.dataReceived(
  542. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\nContent-Type: text/html\r\n\r\n"
  543. % (len(self.end_content),)
  544. + self.end_content
  545. )
  546. # Move the reactor along until we get a response on our original channel
  547. self.pump()
  548. self.assertEqual(channel.code, 200)
  549. self.assertEqual(
  550. channel.json_body, {"og:title": "~matrix~", "og:description": "hi"}
  551. )
  552. # Check that the server received the Accept-Language header as part
  553. # of the request from Synapse
  554. self.assertIn(
  555. (
  556. b"Accept-Language: en-UK\r\n"
  557. b"Accept-Language: en-US;q=0.9\r\n"
  558. b"Accept-Language: fr;q=0.8\r\n"
  559. b"Accept-Language: *;q=0.7"
  560. ),
  561. server.data,
  562. )
  563. def test_nonexistent_image(self) -> None:
  564. """If the preview image doesn't exist, ensure some data is returned."""
  565. self.lookups["matrix.org"] = [(IPv4Address, "10.1.2.3")]
  566. end_content = (
  567. b"""<html><body><img src="http://cdn.matrix.org/foo.jpg"></body></html>"""
  568. )
  569. channel = self.make_request(
  570. "GET",
  571. "preview_url?url=http://matrix.org",
  572. shorthand=False,
  573. await_result=False,
  574. )
  575. self.pump()
  576. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  577. server = AccumulatingProtocol()
  578. server.makeConnection(FakeTransport(client, self.reactor))
  579. client.makeConnection(FakeTransport(server, self.reactor))
  580. client.dataReceived(
  581. (
  582. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  583. b'Content-Type: text/html; charset="utf8"\r\n\r\n'
  584. )
  585. % (len(end_content),)
  586. + end_content
  587. )
  588. self.pump()
  589. self.assertEqual(channel.code, 200)
  590. # The image should not be in the result.
  591. self.assertNotIn("og:image", channel.json_body)
  592. def test_data_url(self) -> None:
  593. """
  594. Requesting to preview a data URL is not supported.
  595. """
  596. self.lookups["matrix.org"] = [(IPv4Address, "10.1.2.3")]
  597. data = base64.b64encode(SMALL_PNG).decode()
  598. query_params = urlencode(
  599. {
  600. "url": f'<html><head><img src="data:image/png;base64,{data}" /></head></html>'
  601. }
  602. )
  603. channel = self.make_request(
  604. "GET",
  605. f"preview_url?{query_params}",
  606. shorthand=False,
  607. )
  608. self.pump()
  609. self.assertEqual(channel.code, 500)
  610. def test_inline_data_url(self) -> None:
  611. """
  612. An inline image (as a data URL) should be parsed properly.
  613. """
  614. self.lookups["matrix.org"] = [(IPv4Address, "10.1.2.3")]
  615. data = base64.b64encode(SMALL_PNG)
  616. end_content = (
  617. b"<html><head>" b'<img src="data:image/png;base64,%s" />' b"</head></html>"
  618. ) % (data,)
  619. channel = self.make_request(
  620. "GET",
  621. "preview_url?url=http://matrix.org",
  622. shorthand=False,
  623. await_result=False,
  624. )
  625. self.pump()
  626. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  627. server = AccumulatingProtocol()
  628. server.makeConnection(FakeTransport(client, self.reactor))
  629. client.makeConnection(FakeTransport(server, self.reactor))
  630. client.dataReceived(
  631. (
  632. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  633. b'Content-Type: text/html; charset="utf8"\r\n\r\n'
  634. )
  635. % (len(end_content),)
  636. + end_content
  637. )
  638. self.pump()
  639. self.assertEqual(channel.code, 200)
  640. self._assert_small_png(channel.json_body)
  641. def test_oembed_photo(self) -> None:
  642. """Test an oEmbed endpoint which returns a 'photo' type which redirects the preview to a new URL."""
  643. self.lookups["publish.twitter.com"] = [(IPv4Address, "10.1.2.3")]
  644. self.lookups["cdn.twitter.com"] = [(IPv4Address, "10.1.2.3")]
  645. result = {
  646. "version": "1.0",
  647. "type": "photo",
  648. "url": "http://cdn.twitter.com/matrixdotorg",
  649. }
  650. oembed_content = json.dumps(result).encode("utf-8")
  651. channel = self.make_request(
  652. "GET",
  653. "preview_url?url=http://twitter.com/matrixdotorg/status/12345",
  654. shorthand=False,
  655. await_result=False,
  656. )
  657. self.pump()
  658. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  659. server = AccumulatingProtocol()
  660. server.makeConnection(FakeTransport(client, self.reactor))
  661. client.makeConnection(FakeTransport(server, self.reactor))
  662. client.dataReceived(
  663. (
  664. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  665. b'Content-Type: application/json; charset="utf8"\r\n\r\n'
  666. )
  667. % (len(oembed_content),)
  668. + oembed_content
  669. )
  670. self.pump()
  671. # Ensure a second request is made to the photo URL.
  672. client = self.reactor.tcpClients[1][2].buildProtocol(None)
  673. server = AccumulatingProtocol()
  674. server.makeConnection(FakeTransport(client, self.reactor))
  675. client.makeConnection(FakeTransport(server, self.reactor))
  676. client.dataReceived(
  677. (
  678. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  679. b"Content-Type: image/png\r\n\r\n"
  680. )
  681. % (len(SMALL_PNG),)
  682. + SMALL_PNG
  683. )
  684. self.pump()
  685. # Ensure the URL is what was requested.
  686. self.assertIn(b"/matrixdotorg", server.data)
  687. self.assertEqual(channel.code, 200)
  688. body = channel.json_body
  689. self.assertEqual(body["og:url"], "http://twitter.com/matrixdotorg/status/12345")
  690. self._assert_small_png(body)
  691. def test_oembed_rich(self) -> None:
  692. """Test an oEmbed endpoint which returns HTML content via the 'rich' type."""
  693. self.lookups["publish.twitter.com"] = [(IPv4Address, "10.1.2.3")]
  694. result = {
  695. "version": "1.0",
  696. "type": "rich",
  697. # Note that this provides the author, not the title.
  698. "author_name": "Alice",
  699. "html": "<div>Content Preview</div>",
  700. }
  701. end_content = json.dumps(result).encode("utf-8")
  702. channel = self.make_request(
  703. "GET",
  704. "preview_url?url=http://twitter.com/matrixdotorg/status/12345",
  705. shorthand=False,
  706. await_result=False,
  707. )
  708. self.pump()
  709. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  710. server = AccumulatingProtocol()
  711. server.makeConnection(FakeTransport(client, self.reactor))
  712. client.makeConnection(FakeTransport(server, self.reactor))
  713. client.dataReceived(
  714. (
  715. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  716. b'Content-Type: application/json; charset="utf8"\r\n\r\n'
  717. )
  718. % (len(end_content),)
  719. + end_content
  720. )
  721. self.pump()
  722. self.assertEqual(channel.code, 200)
  723. body = channel.json_body
  724. self.assertEqual(
  725. body,
  726. {
  727. "og:url": "http://twitter.com/matrixdotorg/status/12345",
  728. "og:title": "Alice",
  729. "og:description": "Content Preview",
  730. },
  731. )
  732. def test_oembed_format(self) -> None:
  733. """Test an oEmbed endpoint which requires the format in the URL."""
  734. self.lookups["www.hulu.com"] = [(IPv4Address, "10.1.2.3")]
  735. result = {
  736. "version": "1.0",
  737. "type": "rich",
  738. "html": "<div>Content Preview</div>",
  739. }
  740. end_content = json.dumps(result).encode("utf-8")
  741. channel = self.make_request(
  742. "GET",
  743. "preview_url?url=http://www.hulu.com/watch/12345",
  744. shorthand=False,
  745. await_result=False,
  746. )
  747. self.pump()
  748. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  749. server = AccumulatingProtocol()
  750. server.makeConnection(FakeTransport(client, self.reactor))
  751. client.makeConnection(FakeTransport(server, self.reactor))
  752. client.dataReceived(
  753. (
  754. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  755. b'Content-Type: application/json; charset="utf8"\r\n\r\n'
  756. )
  757. % (len(end_content),)
  758. + end_content
  759. )
  760. self.pump()
  761. # The {format} should have been turned into json.
  762. self.assertIn(b"/api/oembed.json", server.data)
  763. # A URL parameter of format=json should be provided.
  764. self.assertIn(b"format=json", server.data)
  765. self.assertEqual(channel.code, 200)
  766. body = channel.json_body
  767. self.assertEqual(
  768. body,
  769. {
  770. "og:url": "http://www.hulu.com/watch/12345",
  771. "og:description": "Content Preview",
  772. },
  773. )
  774. def test_oembed_autodiscovery(self) -> None:
  775. """
  776. Autodiscovery works by finding the link in the HTML response and then requesting an oEmbed URL.
  777. 1. Request a preview of a URL which is not known to the oEmbed code.
  778. 2. It returns HTML including a link to an oEmbed preview.
  779. 3. The oEmbed preview is requested and returns a URL for an image.
  780. 4. The image is requested for thumbnailing.
  781. """
  782. # This is a little cheesy in that we use the www subdomain (which isn't the
  783. # list of oEmbed patterns) to get "raw" HTML response.
  784. self.lookups["www.twitter.com"] = [(IPv4Address, "10.1.2.3")]
  785. self.lookups["publish.twitter.com"] = [(IPv4Address, "10.1.2.3")]
  786. self.lookups["cdn.twitter.com"] = [(IPv4Address, "10.1.2.3")]
  787. result = b"""
  788. <link rel="alternate" type="application/json+oembed"
  789. href="http://publish.twitter.com/oembed?url=http%3A%2F%2Fcdn.twitter.com%2Fmatrixdotorg%2Fstatus%2F12345&format=json"
  790. title="matrixdotorg" />
  791. """
  792. channel = self.make_request(
  793. "GET",
  794. "preview_url?url=http://www.twitter.com/matrixdotorg/status/12345",
  795. shorthand=False,
  796. await_result=False,
  797. )
  798. self.pump()
  799. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  800. server = AccumulatingProtocol()
  801. server.makeConnection(FakeTransport(client, self.reactor))
  802. client.makeConnection(FakeTransport(server, self.reactor))
  803. client.dataReceived(
  804. (
  805. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  806. b'Content-Type: text/html; charset="utf8"\r\n\r\n'
  807. )
  808. % (len(result),)
  809. + result
  810. )
  811. self.pump()
  812. # The oEmbed response.
  813. result2 = {
  814. "version": "1.0",
  815. "type": "photo",
  816. "url": "http://cdn.twitter.com/matrixdotorg",
  817. }
  818. oembed_content = json.dumps(result2).encode("utf-8")
  819. # Ensure a second request is made to the oEmbed URL.
  820. client = self.reactor.tcpClients[1][2].buildProtocol(None)
  821. server = AccumulatingProtocol()
  822. server.makeConnection(FakeTransport(client, self.reactor))
  823. client.makeConnection(FakeTransport(server, self.reactor))
  824. client.dataReceived(
  825. (
  826. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  827. b'Content-Type: application/json; charset="utf8"\r\n\r\n'
  828. )
  829. % (len(oembed_content),)
  830. + oembed_content
  831. )
  832. self.pump()
  833. # Ensure the URL is what was requested.
  834. self.assertIn(b"/oembed?", server.data)
  835. # Ensure a third request is made to the photo URL.
  836. client = self.reactor.tcpClients[2][2].buildProtocol(None)
  837. server = AccumulatingProtocol()
  838. server.makeConnection(FakeTransport(client, self.reactor))
  839. client.makeConnection(FakeTransport(server, self.reactor))
  840. client.dataReceived(
  841. (
  842. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  843. b"Content-Type: image/png\r\n\r\n"
  844. )
  845. % (len(SMALL_PNG),)
  846. + SMALL_PNG
  847. )
  848. self.pump()
  849. # Ensure the URL is what was requested.
  850. self.assertIn(b"/matrixdotorg", server.data)
  851. self.assertEqual(channel.code, 200)
  852. body = channel.json_body
  853. self.assertEqual(
  854. body["og:url"], "http://www.twitter.com/matrixdotorg/status/12345"
  855. )
  856. self._assert_small_png(body)
  857. def _download_image(self) -> Tuple[str, str]:
  858. """Downloads an image into the URL cache.
  859. Returns:
  860. A (host, media_id) tuple representing the MXC URI of the image.
  861. """
  862. self.lookups["cdn.twitter.com"] = [(IPv4Address, "10.1.2.3")]
  863. channel = self.make_request(
  864. "GET",
  865. "preview_url?url=http://cdn.twitter.com/matrixdotorg",
  866. shorthand=False,
  867. await_result=False,
  868. )
  869. self.pump()
  870. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  871. server = AccumulatingProtocol()
  872. server.makeConnection(FakeTransport(client, self.reactor))
  873. client.makeConnection(FakeTransport(server, self.reactor))
  874. client.dataReceived(
  875. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\nContent-Type: image/png\r\n\r\n"
  876. % (len(SMALL_PNG),)
  877. + SMALL_PNG
  878. )
  879. self.pump()
  880. self.assertEqual(channel.code, 200)
  881. body = channel.json_body
  882. mxc_uri = body["og:image"]
  883. host, _port, media_id = parse_and_validate_mxc_uri(mxc_uri)
  884. self.assertIsNone(_port)
  885. return host, media_id
  886. def test_storage_providers_exclude_files(self) -> None:
  887. """Test that files are not stored in or fetched from storage providers."""
  888. host, media_id = self._download_image()
  889. rel_file_path = self.preview_url.filepaths.url_cache_filepath_rel(media_id)
  890. media_store_path = os.path.join(self.media_store_path, rel_file_path)
  891. storage_provider_path = os.path.join(self.storage_path, rel_file_path)
  892. # Check storage
  893. self.assertTrue(os.path.isfile(media_store_path))
  894. self.assertFalse(
  895. os.path.isfile(storage_provider_path),
  896. "URL cache file was unexpectedly stored in a storage provider",
  897. )
  898. # Check fetching
  899. channel = self.make_request(
  900. "GET",
  901. f"download/{host}/{media_id}",
  902. shorthand=False,
  903. await_result=False,
  904. )
  905. self.pump()
  906. self.assertEqual(channel.code, 200)
  907. # Move cached file into the storage provider
  908. os.makedirs(os.path.dirname(storage_provider_path), exist_ok=True)
  909. os.rename(media_store_path, storage_provider_path)
  910. channel = self.make_request(
  911. "GET",
  912. f"download/{host}/{media_id}",
  913. shorthand=False,
  914. await_result=False,
  915. )
  916. self.pump()
  917. self.assertEqual(
  918. channel.code,
  919. 404,
  920. "URL cache file was unexpectedly retrieved from a storage provider",
  921. )
  922. def test_storage_providers_exclude_thumbnails(self) -> None:
  923. """Test that thumbnails are not stored in or fetched from storage providers."""
  924. host, media_id = self._download_image()
  925. rel_thumbnail_path = (
  926. self.preview_url.filepaths.url_cache_thumbnail_directory_rel(media_id)
  927. )
  928. media_store_thumbnail_path = os.path.join(
  929. self.media_store_path, rel_thumbnail_path
  930. )
  931. storage_provider_thumbnail_path = os.path.join(
  932. self.storage_path, rel_thumbnail_path
  933. )
  934. # Check storage
  935. self.assertTrue(os.path.isdir(media_store_thumbnail_path))
  936. self.assertFalse(
  937. os.path.isdir(storage_provider_thumbnail_path),
  938. "URL cache thumbnails were unexpectedly stored in a storage provider",
  939. )
  940. # Check fetching
  941. channel = self.make_request(
  942. "GET",
  943. f"thumbnail/{host}/{media_id}?width=32&height=32&method=scale",
  944. shorthand=False,
  945. await_result=False,
  946. )
  947. self.pump()
  948. self.assertEqual(channel.code, 200)
  949. # Remove the original, otherwise thumbnails will regenerate
  950. rel_file_path = self.preview_url.filepaths.url_cache_filepath_rel(media_id)
  951. media_store_path = os.path.join(self.media_store_path, rel_file_path)
  952. os.remove(media_store_path)
  953. # Move cached thumbnails into the storage provider
  954. os.makedirs(os.path.dirname(storage_provider_thumbnail_path), exist_ok=True)
  955. os.rename(media_store_thumbnail_path, storage_provider_thumbnail_path)
  956. channel = self.make_request(
  957. "GET",
  958. f"thumbnail/{host}/{media_id}?width=32&height=32&method=scale",
  959. shorthand=False,
  960. await_result=False,
  961. )
  962. self.pump()
  963. self.assertEqual(
  964. channel.code,
  965. 404,
  966. "URL cache thumbnail was unexpectedly retrieved from a storage provider",
  967. )
  968. def test_cache_expiry(self) -> None:
  969. """Test that URL cache files and thumbnails are cleaned up properly on expiry."""
  970. self.preview_url.clock = MockClock()
  971. _host, media_id = self._download_image()
  972. file_path = self.preview_url.filepaths.url_cache_filepath(media_id)
  973. file_dirs = self.preview_url.filepaths.url_cache_filepath_dirs_to_delete(
  974. media_id
  975. )
  976. thumbnail_dir = self.preview_url.filepaths.url_cache_thumbnail_directory(
  977. media_id
  978. )
  979. thumbnail_dirs = self.preview_url.filepaths.url_cache_thumbnail_dirs_to_delete(
  980. media_id
  981. )
  982. self.assertTrue(os.path.isfile(file_path))
  983. self.assertTrue(os.path.isdir(thumbnail_dir))
  984. self.preview_url.clock.advance_time_msec(IMAGE_CACHE_EXPIRY_MS + 1)
  985. self.get_success(self.preview_url._expire_url_cache_data())
  986. for path in [file_path] + file_dirs + [thumbnail_dir] + thumbnail_dirs:
  987. self.assertFalse(
  988. os.path.exists(path),
  989. f"{os.path.relpath(path, self.media_store_path)} was not deleted",
  990. )
  991. @unittest.override_config({"url_preview_url_blacklist": [{"port": "*"}]})
  992. def test_blacklist_port(self) -> None:
  993. """Tests that blacklisting URLs with a port makes previewing such URLs
  994. fail with a 403 error and doesn't impact other previews.
  995. """
  996. self.lookups["matrix.org"] = [(IPv4Address, "10.1.2.3")]
  997. bad_url = quote("http://matrix.org:8888/foo")
  998. good_url = quote("http://matrix.org/foo")
  999. channel = self.make_request(
  1000. "GET",
  1001. "preview_url?url=" + bad_url,
  1002. shorthand=False,
  1003. await_result=False,
  1004. )
  1005. self.pump()
  1006. self.assertEqual(channel.code, 403, channel.result)
  1007. channel = self.make_request(
  1008. "GET",
  1009. "preview_url?url=" + good_url,
  1010. shorthand=False,
  1011. await_result=False,
  1012. )
  1013. self.pump()
  1014. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  1015. server = AccumulatingProtocol()
  1016. server.makeConnection(FakeTransport(client, self.reactor))
  1017. client.makeConnection(FakeTransport(server, self.reactor))
  1018. client.dataReceived(
  1019. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\nContent-Type: text/html\r\n\r\n"
  1020. % (len(self.end_content),)
  1021. + self.end_content
  1022. )
  1023. self.pump()
  1024. self.assertEqual(channel.code, 200)