RefreshWebcalServiceTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OCA\DAV\Tests\unit\CalDAV\WebcalCaching;
  7. use GuzzleHttp\HandlerStack;
  8. use OCA\DAV\CalDAV\CalDavBackend;
  9. use OCA\DAV\CalDAV\WebcalCaching\RefreshWebcalService;
  10. use OCP\Http\Client\IClient;
  11. use OCP\Http\Client\IClientService;
  12. use OCP\Http\Client\IResponse;
  13. use OCP\Http\Client\LocalServerException;
  14. use OCP\IConfig;
  15. use PHPUnit\Framework\MockObject\MockObject;
  16. use Psr\Log\LoggerInterface;
  17. use Sabre\DAV\Exception\BadRequest;
  18. use Sabre\VObject;
  19. use Sabre\VObject\Recur\NoInstancesException;
  20. use Test\TestCase;
  21. class RefreshWebcalServiceTest extends TestCase {
  22. /** @var CalDavBackend | MockObject */
  23. private $caldavBackend;
  24. /** @var IClientService | MockObject */
  25. private $clientService;
  26. /** @var IConfig | MockObject */
  27. private $config;
  28. /** @var LoggerInterface | MockObject */
  29. private $logger;
  30. protected function setUp(): void {
  31. parent::setUp();
  32. $this->caldavBackend = $this->createMock(CalDavBackend::class);
  33. $this->clientService = $this->createMock(IClientService::class);
  34. $this->config = $this->createMock(IConfig::class);
  35. $this->logger = $this->createMock(LoggerInterface::class);
  36. }
  37. /**
  38. * @param string $body
  39. * @param string $contentType
  40. * @param string $result
  41. *
  42. * @dataProvider runDataProvider
  43. */
  44. public function testRun(string $body, string $contentType, string $result): void {
  45. $refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class)
  46. ->onlyMethods(['getRandomCalendarObjectUri'])
  47. ->setConstructorArgs([$this->caldavBackend, $this->clientService, $this->config, $this->logger])
  48. ->getMock();
  49. $refreshWebcalService
  50. ->method('getRandomCalendarObjectUri')
  51. ->willReturn('uri-1.ics');
  52. $this->caldavBackend->expects($this->once())
  53. ->method('getSubscriptionsForUser')
  54. ->with('principals/users/testuser')
  55. ->willReturn([
  56. [
  57. 'id' => '99',
  58. 'uri' => 'sub456',
  59. '{http://apple.com/ns/ical/}refreshrate' => 'P1D',
  60. '{http://calendarserver.org/ns/}subscribed-strip-todos' => '1',
  61. '{http://calendarserver.org/ns/}subscribed-strip-alarms' => '1',
  62. '{http://calendarserver.org/ns/}subscribed-strip-attachments' => '1',
  63. 'source' => 'webcal://foo.bar/bla'
  64. ],
  65. [
  66. 'id' => '42',
  67. 'uri' => 'sub123',
  68. '{http://apple.com/ns/ical/}refreshrate' => 'PT1H',
  69. '{http://calendarserver.org/ns/}subscribed-strip-todos' => '1',
  70. '{http://calendarserver.org/ns/}subscribed-strip-alarms' => '1',
  71. '{http://calendarserver.org/ns/}subscribed-strip-attachments' => '1',
  72. 'source' => 'webcal://foo.bar/bla2'
  73. ],
  74. ]);
  75. $client = $this->createMock(IClient::class);
  76. $response = $this->createMock(IResponse::class);
  77. $this->clientService->expects($this->once())
  78. ->method('newClient')
  79. ->with()
  80. ->willReturn($client);
  81. $this->config->expects($this->once())
  82. ->method('getAppValue')
  83. ->with('dav', 'webcalAllowLocalAccess', 'no')
  84. ->willReturn('no');
  85. $client->expects($this->once())
  86. ->method('get')
  87. ->with('https://foo.bar/bla2', $this->callback(function ($obj) {
  88. return $obj['allow_redirects']['redirects'] === 10 && $obj['handler'] instanceof HandlerStack;
  89. }))
  90. ->willReturn($response);
  91. $response->expects($this->once())
  92. ->method('getBody')
  93. ->with()
  94. ->willReturn($body);
  95. $response->expects($this->once())
  96. ->method('getHeader')
  97. ->with('Content-Type')
  98. ->willReturn($contentType);
  99. $this->caldavBackend->expects($this->once())
  100. ->method('purgeAllCachedEventsForSubscription')
  101. ->with(42);
  102. $this->caldavBackend->expects($this->once())
  103. ->method('createCalendarObject')
  104. ->with(42, 'uri-1.ics', $result, 1);
  105. $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
  106. }
  107. /**
  108. * @param string $body
  109. * @param string $contentType
  110. * @param string $result
  111. *
  112. * @dataProvider runDataProvider
  113. */
  114. public function testRunCreateCalendarNoException(string $body, string $contentType, string $result): void {
  115. $client = $this->createMock(IClient::class);
  116. $response = $this->createMock(IResponse::class);
  117. $refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class)
  118. ->onlyMethods(['getRandomCalendarObjectUri', 'getSubscription', 'queryWebcalFeed'])
  119. ->setConstructorArgs([$this->caldavBackend, $this->clientService, $this->config, $this->logger])
  120. ->getMock();
  121. $refreshWebcalService
  122. ->method('getRandomCalendarObjectUri')
  123. ->willReturn('uri-1.ics');
  124. $refreshWebcalService
  125. ->method('getSubscription')
  126. ->willReturn([
  127. 'id' => '42',
  128. 'uri' => 'sub123',
  129. '{http://apple.com/ns/ical/}refreshrate' => 'PT1H',
  130. '{http://calendarserver.org/ns/}subscribed-strip-todos' => '1',
  131. '{http://calendarserver.org/ns/}subscribed-strip-alarms' => '1',
  132. '{http://calendarserver.org/ns/}subscribed-strip-attachments' => '1',
  133. 'source' => 'webcal://foo.bar/bla2'
  134. ]);
  135. $this->clientService->expects($this->once())
  136. ->method('newClient')
  137. ->with()
  138. ->willReturn($client);
  139. $this->config->expects($this->once())
  140. ->method('getAppValue')
  141. ->with('dav', 'webcalAllowLocalAccess', 'no')
  142. ->willReturn('no');
  143. $client->expects($this->once())
  144. ->method('get')
  145. ->with('https://foo.bar/bla2', $this->callback(function ($obj) {
  146. return $obj['allow_redirects']['redirects'] === 10 && $obj['handler'] instanceof HandlerStack;
  147. }))
  148. ->willReturn($response);
  149. $response->expects($this->once())
  150. ->method('getBody')
  151. ->with()
  152. ->willReturn($body);
  153. $response->expects($this->once())
  154. ->method('getHeader')
  155. ->with('Content-Type')
  156. ->willReturn($contentType);
  157. $this->caldavBackend->expects($this->once())
  158. ->method('purgeAllCachedEventsForSubscription')
  159. ->with(42);
  160. $this->caldavBackend->expects($this->once())
  161. ->method('createCalendarObject')
  162. ->with(42, 'uri-1.ics', $result, 1);
  163. $noInstanceException = new NoInstancesException("can't add calendar object");
  164. $this->caldavBackend->expects($this->once())
  165. ->method("createCalendarObject")
  166. ->willThrowException($noInstanceException);
  167. $this->logger->expects($this->once())
  168. ->method('error')
  169. ->with('Unable to create calendar object from subscription {subscriptionId}', ['exception' => $noInstanceException, 'subscriptionId' => '42', 'source' => 'webcal://foo.bar/bla2']);
  170. $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
  171. }
  172. /**
  173. * @param string $body
  174. * @param string $contentType
  175. * @param string $result
  176. *
  177. * @dataProvider runDataProvider
  178. */
  179. public function testRunCreateCalendarBadRequest(string $body, string $contentType, string $result): void {
  180. $client = $this->createMock(IClient::class);
  181. $response = $this->createMock(IResponse::class);
  182. $refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class)
  183. ->onlyMethods(['getRandomCalendarObjectUri', 'getSubscription', 'queryWebcalFeed'])
  184. ->setConstructorArgs([$this->caldavBackend, $this->clientService, $this->config, $this->logger])
  185. ->getMock();
  186. $refreshWebcalService
  187. ->method('getRandomCalendarObjectUri')
  188. ->willReturn('uri-1.ics');
  189. $refreshWebcalService
  190. ->method('getSubscription')
  191. ->willReturn([
  192. 'id' => '42',
  193. 'uri' => 'sub123',
  194. '{http://apple.com/ns/ical/}refreshrate' => 'PT1H',
  195. '{http://calendarserver.org/ns/}subscribed-strip-todos' => '1',
  196. '{http://calendarserver.org/ns/}subscribed-strip-alarms' => '1',
  197. '{http://calendarserver.org/ns/}subscribed-strip-attachments' => '1',
  198. 'source' => 'webcal://foo.bar/bla2'
  199. ]);
  200. $this->clientService->expects($this->once())
  201. ->method('newClient')
  202. ->with()
  203. ->willReturn($client);
  204. $this->config->expects($this->once())
  205. ->method('getAppValue')
  206. ->with('dav', 'webcalAllowLocalAccess', 'no')
  207. ->willReturn('no');
  208. $client->expects($this->once())
  209. ->method('get')
  210. ->with('https://foo.bar/bla2', $this->callback(function ($obj) {
  211. return $obj['allow_redirects']['redirects'] === 10 && $obj['handler'] instanceof HandlerStack;
  212. }))
  213. ->willReturn($response);
  214. $response->expects($this->once())
  215. ->method('getBody')
  216. ->with()
  217. ->willReturn($body);
  218. $response->expects($this->once())
  219. ->method('getHeader')
  220. ->with('Content-Type')
  221. ->willReturn($contentType);
  222. $this->caldavBackend->expects($this->once())
  223. ->method('purgeAllCachedEventsForSubscription')
  224. ->with(42);
  225. $this->caldavBackend->expects($this->once())
  226. ->method('createCalendarObject')
  227. ->with(42, 'uri-1.ics', $result, 1);
  228. $badRequestException = new BadRequest("can't add reach calendar url");
  229. $this->caldavBackend->expects($this->once())
  230. ->method("createCalendarObject")
  231. ->willThrowException($badRequestException);
  232. $this->logger->expects($this->once())
  233. ->method('error')
  234. ->with('Unable to create calendar object from subscription {subscriptionId}', ['exception' => $badRequestException, 'subscriptionId' => '42', 'source' => 'webcal://foo.bar/bla2']);
  235. $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
  236. }
  237. /**
  238. * @return array
  239. */
  240. public function runDataProvider():array {
  241. return [
  242. [
  243. "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.1.1//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
  244. 'text/calendar;charset=utf8',
  245. "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject " . VObject\Version::VERSION . "//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
  246. ],
  247. [
  248. '["vcalendar",[["prodid",{},"text","-//Example Corp.//Example Client//EN"],["version",{},"text","2.0"]],[["vtimezone",[["last-modified",{},"date-time","2004-01-10T03:28:45Z"],["tzid",{},"text","US/Eastern"]],[["daylight",[["dtstart",{},"date-time","2000-04-04T02:00:00"],["rrule",{},"recur",{"freq":"YEARLY","byday":"1SU","bymonth":4}],["tzname",{},"text","EDT"],["tzoffsetfrom",{},"utc-offset","-05:00"],["tzoffsetto",{},"utc-offset","-04:00"]],[]],["standard",[["dtstart",{},"date-time","2000-10-26T02:00:00"],["rrule",{},"recur",{"freq":"YEARLY","byday":"1SU","bymonth":10}],["tzname",{},"text","EST"],["tzoffsetfrom",{},"utc-offset","-04:00"],["tzoffsetto",{},"utc-offset","-05:00"]],[]]]],["vevent",[["dtstamp",{},"date-time","2006-02-06T00:11:21Z"],["dtstart",{"tzid":"US/Eastern"},"date-time","2006-01-02T14:00:00"],["duration",{},"duration","PT1H"],["recurrence-id",{"tzid":"US/Eastern"},"date-time","2006-01-04T12:00:00"],["summary",{},"text","Event #2"],["uid",{},"text","12345"]],[]]]]',
  249. 'application/calendar+json',
  250. "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject " . VObject\Version::VERSION . "//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VTIMEZONE\r\nLAST-MODIFIED:20040110T032845Z\r\nTZID:US/Eastern\r\nBEGIN:DAYLIGHT\r\nDTSTART:20000404T020000\r\nRRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4\r\nTZNAME:EDT\r\nTZOFFSETFROM:-0500\r\nTZOFFSETTO:-0400\r\nEND:DAYLIGHT\r\nBEGIN:STANDARD\r\nDTSTART:20001026T020000\r\nRRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=10\r\nTZNAME:EST\r\nTZOFFSETFROM:-0400\r\nTZOFFSETTO:-0500\r\nEND:STANDARD\r\nEND:VTIMEZONE\r\nBEGIN:VEVENT\r\nDTSTAMP:20060206T001121Z\r\nDTSTART;TZID=US/Eastern:20060102T140000\r\nDURATION:PT1H\r\nRECURRENCE-ID;TZID=US/Eastern:20060104T120000\r\nSUMMARY:Event #2\r\nUID:12345\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"
  251. ],
  252. [
  253. '<?xml version="1.0" encoding="utf-8" ?><icalendar xmlns="urn:ietf:params:xml:ns:icalendar-2.0"><vcalendar><properties><prodid><text>-//Example Inc.//Example Client//EN</text></prodid><version><text>2.0</text></version></properties><components><vevent><properties><dtstamp><date-time>2006-02-06T00:11:21Z</date-time></dtstamp><dtstart><parameters><tzid><text>US/Eastern</text></tzid></parameters><date-time>2006-01-04T14:00:00</date-time></dtstart><duration><duration>PT1H</duration></duration><recurrence-id><parameters><tzid><text>US/Eastern</text></tzid></parameters><date-time>2006-01-04T12:00:00</date-time></recurrence-id><summary><text>Event #2 bis</text></summary><uid><text>12345</text></uid></properties></vevent></components></vcalendar></icalendar>',
  254. 'application/calendar+xml',
  255. "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject " . VObject\Version::VERSION . "//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nDTSTAMP:20060206T001121Z\r\nDTSTART;TZID=US/Eastern:20060104T140000\r\nDURATION:PT1H\r\nRECURRENCE-ID;TZID=US/Eastern:20060104T120000\r\nSUMMARY:Event #2 bis\r\nUID:12345\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"
  256. ]
  257. ];
  258. }
  259. /**
  260. * @dataProvider runLocalURLDataProvider
  261. */
  262. public function testRunLocalURL(string $source): void {
  263. $refreshWebcalService = new RefreshWebcalService(
  264. $this->caldavBackend,
  265. $this->clientService,
  266. $this->config,
  267. $this->logger
  268. );
  269. $this->caldavBackend->expects($this->once())
  270. ->method('getSubscriptionsForUser')
  271. ->with('principals/users/testuser')
  272. ->willReturn([
  273. [
  274. 'id' => 42,
  275. 'uri' => 'sub123',
  276. 'refreshreate' => 'P1H',
  277. 'striptodos' => 1,
  278. 'stripalarms' => 1,
  279. 'stripattachments' => 1,
  280. 'source' => $source
  281. ],
  282. ]);
  283. $client = $this->createMock(IClient::class);
  284. $this->clientService->expects($this->once())
  285. ->method('newClient')
  286. ->with()
  287. ->willReturn($client);
  288. $this->config->expects($this->once())
  289. ->method('getAppValue')
  290. ->with('dav', 'webcalAllowLocalAccess', 'no')
  291. ->willReturn('no');
  292. $localServerException = new LocalServerException();
  293. $client->expects($this->once())
  294. ->method('get')
  295. ->willThrowException($localServerException);
  296. $this->logger->expects($this->once())
  297. ->method('warning')
  298. ->with("Subscription 42 was not refreshed because it violates local access rules", ['exception' => $localServerException]);
  299. $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
  300. }
  301. public function runLocalURLDataProvider():array {
  302. return [
  303. ['localhost/foo.bar'],
  304. ['localHost/foo.bar'],
  305. ['random-host/foo.bar'],
  306. ['[::1]/bla.blub'],
  307. ['[::]/bla.blub'],
  308. ['192.168.0.1'],
  309. ['172.16.42.1'],
  310. ['[fdf8:f53b:82e4::53]/secret.ics'],
  311. ['[fe80::200:5aee:feaa:20a2]/secret.ics'],
  312. ['[0:0:0:0:0:0:10.0.0.1]/secret.ics'],
  313. ['[0:0:0:0:0:ffff:127.0.0.0]/secret.ics'],
  314. ['10.0.0.1'],
  315. ['another-host.local'],
  316. ['service.localhost'],
  317. ];
  318. }
  319. public function testInvalidUrl(): void {
  320. $refreshWebcalService = new RefreshWebcalService($this->caldavBackend,
  321. $this->clientService, $this->config, $this->logger);
  322. $this->caldavBackend->expects($this->once())
  323. ->method('getSubscriptionsForUser')
  324. ->with('principals/users/testuser')
  325. ->willReturn([
  326. [
  327. 'id' => 42,
  328. 'uri' => 'sub123',
  329. 'refreshreate' => 'P1H',
  330. 'striptodos' => 1,
  331. 'stripalarms' => 1,
  332. 'stripattachments' => 1,
  333. 'source' => '!@#$'
  334. ],
  335. ]);
  336. $client = $this->createMock(IClient::class);
  337. $this->clientService->expects($this->once())
  338. ->method('newClient')
  339. ->with()
  340. ->willReturn($client);
  341. $this->config->expects($this->once())
  342. ->method('getAppValue')
  343. ->with('dav', 'webcalAllowLocalAccess', 'no')
  344. ->willReturn('no');
  345. $client->expects($this->never())
  346. ->method('get');
  347. $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
  348. }
  349. }