test_url_preview.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  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.media_repository_resource import MediaRepositoryResource
  28. from synapse.rest.media.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.media.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. 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.preview_url.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.preview_url.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.preview_url.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. self.preview_url.clock = MockClock()
  1003. _host, media_id = self._download_image()
  1004. file_path = self.preview_url.filepaths.url_cache_filepath(media_id)
  1005. file_dirs = self.preview_url.filepaths.url_cache_filepath_dirs_to_delete(
  1006. media_id
  1007. )
  1008. thumbnail_dir = self.preview_url.filepaths.url_cache_thumbnail_directory(
  1009. media_id
  1010. )
  1011. thumbnail_dirs = self.preview_url.filepaths.url_cache_thumbnail_dirs_to_delete(
  1012. media_id
  1013. )
  1014. self.assertTrue(os.path.isfile(file_path))
  1015. self.assertTrue(os.path.isdir(thumbnail_dir))
  1016. self.preview_url.clock.advance_time_msec(IMAGE_CACHE_EXPIRY_MS + 1)
  1017. self.get_success(self.preview_url._expire_url_cache_data())
  1018. for path in [file_path] + file_dirs + [thumbnail_dir] + thumbnail_dirs:
  1019. self.assertFalse(
  1020. os.path.exists(path),
  1021. f"{os.path.relpath(path, self.media_store_path)} was not deleted",
  1022. )
  1023. @unittest.override_config({"url_preview_url_blacklist": [{"port": "*"}]})
  1024. def test_blacklist_port(self) -> None:
  1025. """Tests that blacklisting URLs with a port makes previewing such URLs
  1026. fail with a 403 error and doesn't impact other previews.
  1027. """
  1028. self.lookups["matrix.org"] = [(IPv4Address, "10.1.2.3")]
  1029. bad_url = quote("http://matrix.org:8888/foo")
  1030. good_url = quote("http://matrix.org/foo")
  1031. channel = self.make_request(
  1032. "GET",
  1033. "preview_url?url=" + bad_url,
  1034. shorthand=False,
  1035. await_result=False,
  1036. )
  1037. self.pump()
  1038. self.assertEqual(channel.code, 403, channel.result)
  1039. channel = self.make_request(
  1040. "GET",
  1041. "preview_url?url=" + good_url,
  1042. shorthand=False,
  1043. await_result=False,
  1044. )
  1045. self.pump()
  1046. client = self.reactor.tcpClients[0][2].buildProtocol(None)
  1047. server = AccumulatingProtocol()
  1048. server.makeConnection(FakeTransport(client, self.reactor))
  1049. client.makeConnection(FakeTransport(server, self.reactor))
  1050. client.dataReceived(
  1051. b"HTTP/1.0 200 OK\r\nContent-Length: %d\r\nContent-Type: text/html\r\n\r\n"
  1052. % (len(self.end_content),)
  1053. + self.end_content
  1054. )
  1055. self.pump()
  1056. self.assertEqual(channel.code, 200)