test_url_preview.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  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.media.url_previewer import IMAGE_CACHE_EXPIRY_MS
  28. from synapse.rest.media.media_repository_resource import MediaRepositoryResource
  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. try:
  37. import lxml
  38. except ImportError:
  39. lxml = None
  40. class URLPreviewTests(unittest.HomeserverTestCase):
  41. if not lxml:
  42. skip = "url preview feature requires lxml"
  43. hijack_auth = True
  44. user_id = "@test:user"
  45. end_content = (
  46. b"<html><head>"
  47. b'<meta property="og:title" content="~matrix~" />'
  48. b'<meta property="og:description" content="hi" />'
  49. b"</head></html>"
  50. )
  51. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  52. config = self.default_config()
  53. config["url_preview_enabled"] = True
  54. config["max_spider_size"] = 9999999
  55. config["url_preview_ip_range_blacklist"] = (
  56. "192.168.1.1",
  57. "1.0.0.0/8",
  58. "3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
  59. "2001:800::/21",
  60. )
  61. config["url_preview_ip_range_whitelist"] = ("1.1.1.1",)
  62. config["url_preview_accept_language"] = [
  63. "en-UK",
  64. "en-US;q=0.9",
  65. "fr;q=0.8",
  66. "*;q=0.7",
  67. ]
  68. self.storage_path = self.mktemp()
  69. self.media_store_path = self.mktemp()
  70. os.mkdir(self.storage_path)
  71. os.mkdir(self.media_store_path)
  72. config["media_store_path"] = self.media_store_path
  73. provider_config = {
  74. "module": "synapse.media.storage_provider.FileStorageProviderBackend",
  75. "store_local": True,
  76. "store_synchronous": False,
  77. "store_remote": True,
  78. "config": {"directory": self.storage_path},
  79. }
  80. config["media_storage_providers"] = [provider_config]
  81. hs = self.setup_test_homeserver(config=config)
  82. # After the hs is created, modify the parsed oEmbed config (to avoid
  83. # messing with files).
  84. #
  85. # Note that HTTP URLs are used to avoid having to deal with TLS in tests.
  86. hs.config.oembed.oembed_patterns = [
  87. OEmbedEndpointConfig(
  88. api_endpoint="http://publish.twitter.com/oembed",
  89. url_patterns=[
  90. re.compile(r"http://twitter\.com/.+/status/.+"),
  91. ],
  92. formats=None,
  93. ),
  94. OEmbedEndpointConfig(
  95. api_endpoint="http://www.hulu.com/api/oembed.{format}",
  96. url_patterns=[
  97. re.compile(r"http://www\.hulu\.com/watch/.+"),
  98. ],
  99. formats=["json"],
  100. ),
  101. ]
  102. return hs
  103. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  104. self.media_repo = hs.get_media_repository()
  105. media_repo_resource = hs.get_media_repository_resource()
  106. self.preview_url = media_repo_resource.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._url_previewer._cache)
  169. self.preview_url._url_previewer._cache.pop("http://matrix.org")
  170. self.assertNotIn("http://matrix.org", self.preview_url._url_previewer._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. result = (
  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(result),)
  586. + result
  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_oembed_failure(self) -> None:
  593. """If the autodiscovered oEmbed URL fails, ensure some data is returned."""
  594. self.lookups["matrix.org"] = [(IPv4Address, "10.1.2.3")]
  595. result = b"""
  596. <title>oEmbed Autodiscovery Fail</title>
  597. <link rel="alternate" type="application/json+oembed"
  598. href="http://example.com/oembed?url=http%3A%2F%2Fmatrix.org&format=json"
  599. title="matrixdotorg" />
  600. """
  601. channel = self.make_request(
  602. "GET",
  603. "preview_url?url=http://matrix.org",
  604. shorthand=False,
  605. await_result=False,
  606. )
  607. self.pump()
  608. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  609. server = AccumulatingProtocol()
  610. server.makeConnection(FakeTransport(client, self.reactor))
  611. client.makeConnection(FakeTransport(server, self.reactor))
  612. client.dataReceived(
  613. (
  614. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  615. b'Content-Type: text/html; charset="utf8"\r\n\r\n'
  616. )
  617. % (len(result),)
  618. + result
  619. )
  620. self.pump()
  621. self.assertEqual(channel.code, 200)
  622. # The image should not be in the result.
  623. self.assertEqual(channel.json_body["og:title"], "oEmbed Autodiscovery Fail")
  624. def test_data_url(self) -> None:
  625. """
  626. Requesting to preview a data URL is not supported.
  627. """
  628. self.lookups["matrix.org"] = [(IPv4Address, "10.1.2.3")]
  629. data = base64.b64encode(SMALL_PNG).decode()
  630. query_params = urlencode(
  631. {
  632. "url": f'<html><head><img src="data:image/png;base64,{data}" /></head></html>'
  633. }
  634. )
  635. channel = self.make_request(
  636. "GET",
  637. f"preview_url?{query_params}",
  638. shorthand=False,
  639. )
  640. self.pump()
  641. self.assertEqual(channel.code, 500)
  642. def test_inline_data_url(self) -> None:
  643. """
  644. An inline image (as a data URL) should be parsed properly.
  645. """
  646. self.lookups["matrix.org"] = [(IPv4Address, "10.1.2.3")]
  647. data = base64.b64encode(SMALL_PNG)
  648. end_content = (
  649. b"<html><head>" b'<img src="data:image/png;base64,%s" />' b"</head></html>"
  650. ) % (data,)
  651. channel = self.make_request(
  652. "GET",
  653. "preview_url?url=http://matrix.org",
  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: text/html; charset="utf8"\r\n\r\n'
  666. )
  667. % (len(end_content),)
  668. + end_content
  669. )
  670. self.pump()
  671. self.assertEqual(channel.code, 200)
  672. self._assert_small_png(channel.json_body)
  673. def test_oembed_photo(self) -> None:
  674. """Test an oEmbed endpoint which returns a 'photo' type which redirects the preview to a new URL."""
  675. self.lookups["publish.twitter.com"] = [(IPv4Address, "10.1.2.3")]
  676. self.lookups["cdn.twitter.com"] = [(IPv4Address, "10.1.2.3")]
  677. result = {
  678. "version": "1.0",
  679. "type": "photo",
  680. "url": "http://cdn.twitter.com/matrixdotorg",
  681. }
  682. oembed_content = json.dumps(result).encode("utf-8")
  683. channel = self.make_request(
  684. "GET",
  685. "preview_url?url=http://twitter.com/matrixdotorg/status/12345",
  686. shorthand=False,
  687. await_result=False,
  688. )
  689. self.pump()
  690. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  691. server = AccumulatingProtocol()
  692. server.makeConnection(FakeTransport(client, self.reactor))
  693. client.makeConnection(FakeTransport(server, self.reactor))
  694. client.dataReceived(
  695. (
  696. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  697. b'Content-Type: application/json; charset="utf8"\r\n\r\n'
  698. )
  699. % (len(oembed_content),)
  700. + oembed_content
  701. )
  702. self.pump()
  703. # Ensure a second request is made to the photo URL.
  704. client = self.reactor.tcpClients[1][2].buildProtocol(None)
  705. server = AccumulatingProtocol()
  706. server.makeConnection(FakeTransport(client, self.reactor))
  707. client.makeConnection(FakeTransport(server, self.reactor))
  708. client.dataReceived(
  709. (
  710. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  711. b"Content-Type: image/png\r\n\r\n"
  712. )
  713. % (len(SMALL_PNG),)
  714. + SMALL_PNG
  715. )
  716. self.pump()
  717. # Ensure the URL is what was requested.
  718. self.assertIn(b"/matrixdotorg", server.data)
  719. self.assertEqual(channel.code, 200)
  720. body = channel.json_body
  721. self.assertEqual(body["og:url"], "http://twitter.com/matrixdotorg/status/12345")
  722. self._assert_small_png(body)
  723. def test_oembed_rich(self) -> None:
  724. """Test an oEmbed endpoint which returns HTML content via the 'rich' type."""
  725. self.lookups["publish.twitter.com"] = [(IPv4Address, "10.1.2.3")]
  726. result = {
  727. "version": "1.0",
  728. "type": "rich",
  729. # Note that this provides the author, not the title.
  730. "author_name": "Alice",
  731. "html": "<div>Content Preview</div>",
  732. }
  733. end_content = json.dumps(result).encode("utf-8")
  734. channel = self.make_request(
  735. "GET",
  736. "preview_url?url=http://twitter.com/matrixdotorg/status/12345",
  737. shorthand=False,
  738. await_result=False,
  739. )
  740. self.pump()
  741. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  742. server = AccumulatingProtocol()
  743. server.makeConnection(FakeTransport(client, self.reactor))
  744. client.makeConnection(FakeTransport(server, self.reactor))
  745. client.dataReceived(
  746. (
  747. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  748. b'Content-Type: application/json; charset="utf8"\r\n\r\n'
  749. )
  750. % (len(end_content),)
  751. + end_content
  752. )
  753. self.pump()
  754. self.assertEqual(channel.code, 200)
  755. body = channel.json_body
  756. self.assertEqual(
  757. body,
  758. {
  759. "og:url": "http://twitter.com/matrixdotorg/status/12345",
  760. "og:title": "Alice",
  761. "og:description": "Content Preview",
  762. },
  763. )
  764. def test_oembed_format(self) -> None:
  765. """Test an oEmbed endpoint which requires the format in the URL."""
  766. self.lookups["www.hulu.com"] = [(IPv4Address, "10.1.2.3")]
  767. result = {
  768. "version": "1.0",
  769. "type": "rich",
  770. "html": "<div>Content Preview</div>",
  771. }
  772. end_content = json.dumps(result).encode("utf-8")
  773. channel = self.make_request(
  774. "GET",
  775. "preview_url?url=http://www.hulu.com/watch/12345",
  776. shorthand=False,
  777. await_result=False,
  778. )
  779. self.pump()
  780. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  781. server = AccumulatingProtocol()
  782. server.makeConnection(FakeTransport(client, self.reactor))
  783. client.makeConnection(FakeTransport(server, self.reactor))
  784. client.dataReceived(
  785. (
  786. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  787. b'Content-Type: application/json; charset="utf8"\r\n\r\n'
  788. )
  789. % (len(end_content),)
  790. + end_content
  791. )
  792. self.pump()
  793. # The {format} should have been turned into json.
  794. self.assertIn(b"/api/oembed.json", server.data)
  795. # A URL parameter of format=json should be provided.
  796. self.assertIn(b"format=json", server.data)
  797. self.assertEqual(channel.code, 200)
  798. body = channel.json_body
  799. self.assertEqual(
  800. body,
  801. {
  802. "og:url": "http://www.hulu.com/watch/12345",
  803. "og:description": "Content Preview",
  804. },
  805. )
  806. def test_oembed_autodiscovery(self) -> None:
  807. """
  808. Autodiscovery works by finding the link in the HTML response and then requesting an oEmbed URL.
  809. 1. Request a preview of a URL which is not known to the oEmbed code.
  810. 2. It returns HTML including a link to an oEmbed preview.
  811. 3. The oEmbed preview is requested and returns a URL for an image.
  812. 4. The image is requested for thumbnailing.
  813. """
  814. # This is a little cheesy in that we use the www subdomain (which isn't the
  815. # list of oEmbed patterns) to get "raw" HTML response.
  816. self.lookups["www.twitter.com"] = [(IPv4Address, "10.1.2.3")]
  817. self.lookups["publish.twitter.com"] = [(IPv4Address, "10.1.2.3")]
  818. self.lookups["cdn.twitter.com"] = [(IPv4Address, "10.1.2.3")]
  819. result = b"""
  820. <link rel="alternate" type="application/json+oembed"
  821. href="http://publish.twitter.com/oembed?url=http%3A%2F%2Fcdn.twitter.com%2Fmatrixdotorg%2Fstatus%2F12345&format=json"
  822. title="matrixdotorg" />
  823. """
  824. channel = self.make_request(
  825. "GET",
  826. "preview_url?url=http://www.twitter.com/matrixdotorg/status/12345",
  827. shorthand=False,
  828. await_result=False,
  829. )
  830. self.pump()
  831. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  832. server = AccumulatingProtocol()
  833. server.makeConnection(FakeTransport(client, self.reactor))
  834. client.makeConnection(FakeTransport(server, self.reactor))
  835. client.dataReceived(
  836. (
  837. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  838. b'Content-Type: text/html; charset="utf8"\r\n\r\n'
  839. )
  840. % (len(result),)
  841. + result
  842. )
  843. self.pump()
  844. # The oEmbed response.
  845. result2 = {
  846. "version": "1.0",
  847. "type": "photo",
  848. "url": "http://cdn.twitter.com/matrixdotorg",
  849. }
  850. oembed_content = json.dumps(result2).encode("utf-8")
  851. # Ensure a second request is made to the oEmbed URL.
  852. client = self.reactor.tcpClients[1][2].buildProtocol(None)
  853. server = AccumulatingProtocol()
  854. server.makeConnection(FakeTransport(client, self.reactor))
  855. client.makeConnection(FakeTransport(server, self.reactor))
  856. client.dataReceived(
  857. (
  858. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  859. b'Content-Type: application/json; charset="utf8"\r\n\r\n'
  860. )
  861. % (len(oembed_content),)
  862. + oembed_content
  863. )
  864. self.pump()
  865. # Ensure the URL is what was requested.
  866. self.assertIn(b"/oembed?", server.data)
  867. # Ensure a third request is made to the photo URL.
  868. client = self.reactor.tcpClients[2][2].buildProtocol(None)
  869. server = AccumulatingProtocol()
  870. server.makeConnection(FakeTransport(client, self.reactor))
  871. client.makeConnection(FakeTransport(server, self.reactor))
  872. client.dataReceived(
  873. (
  874. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\n"
  875. b"Content-Type: image/png\r\n\r\n"
  876. )
  877. % (len(SMALL_PNG),)
  878. + SMALL_PNG
  879. )
  880. self.pump()
  881. # Ensure the URL is what was requested.
  882. self.assertIn(b"/matrixdotorg", server.data)
  883. self.assertEqual(channel.code, 200)
  884. body = channel.json_body
  885. self.assertEqual(
  886. body["og:url"], "http://www.twitter.com/matrixdotorg/status/12345"
  887. )
  888. self._assert_small_png(body)
  889. def _download_image(self) -> Tuple[str, str]:
  890. """Downloads an image into the URL cache.
  891. Returns:
  892. A (host, media_id) tuple representing the MXC URI of the image.
  893. """
  894. self.lookups["cdn.twitter.com"] = [(IPv4Address, "10.1.2.3")]
  895. channel = self.make_request(
  896. "GET",
  897. "preview_url?url=http://cdn.twitter.com/matrixdotorg",
  898. shorthand=False,
  899. await_result=False,
  900. )
  901. self.pump()
  902. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  903. server = AccumulatingProtocol()
  904. server.makeConnection(FakeTransport(client, self.reactor))
  905. client.makeConnection(FakeTransport(server, self.reactor))
  906. client.dataReceived(
  907. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\nContent-Type: image/png\r\n\r\n"
  908. % (len(SMALL_PNG),)
  909. + SMALL_PNG
  910. )
  911. self.pump()
  912. self.assertEqual(channel.code, 200)
  913. body = channel.json_body
  914. mxc_uri = body["og:image"]
  915. host, _port, media_id = parse_and_validate_mxc_uri(mxc_uri)
  916. self.assertIsNone(_port)
  917. return host, media_id
  918. def test_storage_providers_exclude_files(self) -> None:
  919. """Test that files are not stored in or fetched from storage providers."""
  920. host, media_id = self._download_image()
  921. rel_file_path = self.media_repo.filepaths.url_cache_filepath_rel(media_id)
  922. media_store_path = os.path.join(self.media_store_path, rel_file_path)
  923. storage_provider_path = os.path.join(self.storage_path, rel_file_path)
  924. # Check storage
  925. self.assertTrue(os.path.isfile(media_store_path))
  926. self.assertFalse(
  927. os.path.isfile(storage_provider_path),
  928. "URL cache file was unexpectedly stored in a storage provider",
  929. )
  930. # Check fetching
  931. channel = self.make_request(
  932. "GET",
  933. f"download/{host}/{media_id}",
  934. shorthand=False,
  935. await_result=False,
  936. )
  937. self.pump()
  938. self.assertEqual(channel.code, 200)
  939. # Move cached file into the storage provider
  940. os.makedirs(os.path.dirname(storage_provider_path), exist_ok=True)
  941. os.rename(media_store_path, storage_provider_path)
  942. channel = self.make_request(
  943. "GET",
  944. f"download/{host}/{media_id}",
  945. shorthand=False,
  946. await_result=False,
  947. )
  948. self.pump()
  949. self.assertEqual(
  950. channel.code,
  951. 404,
  952. "URL cache file was unexpectedly retrieved from a storage provider",
  953. )
  954. def test_storage_providers_exclude_thumbnails(self) -> None:
  955. """Test that thumbnails are not stored in or fetched from storage providers."""
  956. host, media_id = self._download_image()
  957. rel_thumbnail_path = (
  958. self.media_repo.filepaths.url_cache_thumbnail_directory_rel(media_id)
  959. )
  960. media_store_thumbnail_path = os.path.join(
  961. self.media_store_path, rel_thumbnail_path
  962. )
  963. storage_provider_thumbnail_path = os.path.join(
  964. self.storage_path, rel_thumbnail_path
  965. )
  966. # Check storage
  967. self.assertTrue(os.path.isdir(media_store_thumbnail_path))
  968. self.assertFalse(
  969. os.path.isdir(storage_provider_thumbnail_path),
  970. "URL cache thumbnails were unexpectedly stored in a storage provider",
  971. )
  972. # Check fetching
  973. channel = self.make_request(
  974. "GET",
  975. f"thumbnail/{host}/{media_id}?width=32&height=32&method=scale",
  976. shorthand=False,
  977. await_result=False,
  978. )
  979. self.pump()
  980. self.assertEqual(channel.code, 200)
  981. # Remove the original, otherwise thumbnails will regenerate
  982. rel_file_path = self.media_repo.filepaths.url_cache_filepath_rel(media_id)
  983. media_store_path = os.path.join(self.media_store_path, rel_file_path)
  984. os.remove(media_store_path)
  985. # Move cached thumbnails into the storage provider
  986. os.makedirs(os.path.dirname(storage_provider_thumbnail_path), exist_ok=True)
  987. os.rename(media_store_thumbnail_path, storage_provider_thumbnail_path)
  988. channel = self.make_request(
  989. "GET",
  990. f"thumbnail/{host}/{media_id}?width=32&height=32&method=scale",
  991. shorthand=False,
  992. await_result=False,
  993. )
  994. self.pump()
  995. self.assertEqual(
  996. channel.code,
  997. 404,
  998. "URL cache thumbnail was unexpectedly retrieved from a storage provider",
  999. )
  1000. def test_cache_expiry(self) -> None:
  1001. """Test that URL cache files and thumbnails are cleaned up properly on expiry."""
  1002. _host, media_id = self._download_image()
  1003. file_path = self.media_repo.filepaths.url_cache_filepath(media_id)
  1004. file_dirs = self.media_repo.filepaths.url_cache_filepath_dirs_to_delete(
  1005. media_id
  1006. )
  1007. thumbnail_dir = self.media_repo.filepaths.url_cache_thumbnail_directory(
  1008. media_id
  1009. )
  1010. thumbnail_dirs = self.media_repo.filepaths.url_cache_thumbnail_dirs_to_delete(
  1011. media_id
  1012. )
  1013. self.assertTrue(os.path.isfile(file_path))
  1014. self.assertTrue(os.path.isdir(thumbnail_dir))
  1015. self.reactor.advance(IMAGE_CACHE_EXPIRY_MS * 1000 + 1)
  1016. self.get_success(self.preview_url._url_previewer._expire_url_cache_data())
  1017. for path in [file_path] + file_dirs + [thumbnail_dir] + thumbnail_dirs:
  1018. self.assertFalse(
  1019. os.path.exists(path),
  1020. f"{os.path.relpath(path, self.media_store_path)} was not deleted",
  1021. )
  1022. @unittest.override_config({"url_preview_url_blacklist": [{"port": "*"}]})
  1023. def test_blacklist_port(self) -> None:
  1024. """Tests that blacklisting URLs with a port makes previewing such URLs
  1025. fail with a 403 error and doesn't impact other previews.
  1026. """
  1027. self.lookups["matrix.org"] = [(IPv4Address, "10.1.2.3")]
  1028. bad_url = quote("http://matrix.org:8888/foo")
  1029. good_url = quote("http://matrix.org/foo")
  1030. channel = self.make_request(
  1031. "GET",
  1032. "preview_url?url=" + bad_url,
  1033. shorthand=False,
  1034. await_result=False,
  1035. )
  1036. self.pump()
  1037. self.assertEqual(channel.code, 403, channel.result)
  1038. channel = self.make_request(
  1039. "GET",
  1040. "preview_url?url=" + good_url,
  1041. shorthand=False,
  1042. await_result=False,
  1043. )
  1044. self.pump()
  1045. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  1046. server = AccumulatingProtocol()
  1047. server.makeConnection(FakeTransport(client, self.reactor))
  1048. client.makeConnection(FakeTransport(server, self.reactor))
  1049. client.dataReceived(
  1050. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\nContent-Type: text/html\r\n\r\n"
  1051. % (len(self.end_content),)
  1052. + self.end_content
  1053. )
  1054. self.pump()
  1055. self.assertEqual(channel.code, 200)