FileTest.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
  7. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Robin Appelman <robin@icewind.nl>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. * @author Vincent Petry <vincent@nextcloud.com>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OCA\DAV\Tests\unit\Connector\Sabre;
  31. use OC\AppFramework\Http\Request;
  32. use OC\Files\Filesystem;
  33. use OC\Files\Storage\Local;
  34. use OC\Files\Storage\Temporary;
  35. use OC\Files\Storage\Wrapper\PermissionsMask;
  36. use OC\Files\View;
  37. use OCA\DAV\Connector\Sabre\File;
  38. use OCP\Constants;
  39. use OCP\Files\FileInfo;
  40. use OCP\Files\ForbiddenException;
  41. use OCP\Files\Storage;
  42. use OCP\IConfig;
  43. use OCP\IRequestId;
  44. use OCP\Lock\ILockingProvider;
  45. use PHPUnit\Framework\MockObject\MockObject;
  46. use Test\HookHelper;
  47. use Test\TestCase;
  48. use Test\Traits\MountProviderTrait;
  49. use Test\Traits\UserTrait;
  50. /**
  51. * Class File
  52. *
  53. * @group DB
  54. *
  55. * @package OCA\DAV\Tests\unit\Connector\Sabre
  56. */
  57. class FileTest extends TestCase {
  58. use MountProviderTrait;
  59. use UserTrait;
  60. /**
  61. * @var string
  62. */
  63. private $user;
  64. /** @var IConfig|MockObject */
  65. protected $config;
  66. /** @var IRequestId|MockObject */
  67. protected $requestId;
  68. protected function setUp(): void {
  69. parent::setUp();
  70. \OC_Hook::clear();
  71. $this->user = 'test_user';
  72. $this->createUser($this->user, 'pass');
  73. $this->loginAsUser($this->user);
  74. $this->config = $this->createMock(IConfig::class);
  75. $this->requestId = $this->createMock(IRequestId::class);
  76. }
  77. protected function tearDown(): void {
  78. $userManager = \OC::$server->getUserManager();
  79. $userManager->get($this->user)->delete();
  80. parent::tearDown();
  81. }
  82. /**
  83. * @return MockObject|Storage
  84. */
  85. private function getMockStorage() {
  86. $storage = $this->getMockBuilder(Storage::class)
  87. ->disableOriginalConstructor()
  88. ->getMock();
  89. $storage->method('getId')
  90. ->willReturn('home::someuser');
  91. return $storage;
  92. }
  93. /**
  94. * @param string $string
  95. */
  96. private function getStream($string) {
  97. $stream = fopen('php://temp', 'r+');
  98. fwrite($stream, $string);
  99. fseek($stream, 0);
  100. return $stream;
  101. }
  102. public function fopenFailuresProvider() {
  103. return [
  104. [
  105. // return false
  106. null,
  107. '\Sabre\Dav\Exception',
  108. false
  109. ],
  110. [
  111. new \OCP\Files\NotPermittedException(),
  112. 'Sabre\DAV\Exception\Forbidden'
  113. ],
  114. [
  115. new \OCP\Files\EntityTooLargeException(),
  116. 'OCA\DAV\Connector\Sabre\Exception\EntityTooLarge'
  117. ],
  118. [
  119. new \OCP\Files\InvalidContentException(),
  120. 'OCA\DAV\Connector\Sabre\Exception\UnsupportedMediaType'
  121. ],
  122. [
  123. new \OCP\Files\InvalidPathException(),
  124. 'Sabre\DAV\Exception\Forbidden'
  125. ],
  126. [
  127. new \OCP\Files\ForbiddenException('', true),
  128. 'OCA\DAV\Connector\Sabre\Exception\Forbidden'
  129. ],
  130. [
  131. new \OCP\Files\LockNotAcquiredException('/test.txt', 1),
  132. 'OCA\DAV\Connector\Sabre\Exception\FileLocked'
  133. ],
  134. [
  135. new \OCP\Lock\LockedException('/test.txt'),
  136. 'OCA\DAV\Connector\Sabre\Exception\FileLocked'
  137. ],
  138. [
  139. new \OCP\Encryption\Exceptions\GenericEncryptionException(),
  140. 'Sabre\DAV\Exception\ServiceUnavailable'
  141. ],
  142. [
  143. new \OCP\Files\StorageNotAvailableException(),
  144. 'Sabre\DAV\Exception\ServiceUnavailable'
  145. ],
  146. [
  147. new \Sabre\DAV\Exception('Generic sabre exception'),
  148. 'Sabre\DAV\Exception',
  149. false
  150. ],
  151. [
  152. new \Exception('Generic exception'),
  153. 'Sabre\DAV\Exception'
  154. ],
  155. ];
  156. }
  157. /**
  158. * @dataProvider fopenFailuresProvider
  159. */
  160. public function testSimplePutFails($thrownException, $expectedException, $checkPreviousClass = true): void {
  161. // setup
  162. $storage = $this->getMockBuilder(Local::class)
  163. ->setMethods(['writeStream'])
  164. ->setConstructorArgs([['datadir' => \OC::$server->getTempManager()->getTemporaryFolder()]])
  165. ->getMock();
  166. \OC\Files\Filesystem::mount($storage, [], $this->user . '/');
  167. /** @var View | MockObject $view */
  168. $view = $this->getMockBuilder(View::class)
  169. ->setMethods(['getRelativePath', 'resolvePath'])
  170. ->getMock();
  171. $view->expects($this->atLeastOnce())
  172. ->method('resolvePath')
  173. ->willReturnCallback(
  174. function ($path) use ($storage) {
  175. return [$storage, $path];
  176. }
  177. );
  178. if ($thrownException !== null) {
  179. $storage->expects($this->once())
  180. ->method('writeStream')
  181. ->will($this->throwException($thrownException));
  182. } else {
  183. $storage->expects($this->once())
  184. ->method('writeStream')
  185. ->willReturn(0);
  186. }
  187. $view->expects($this->any())
  188. ->method('getRelativePath')
  189. ->willReturnArgument(0);
  190. $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [
  191. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  192. 'type' => FileInfo::TYPE_FOLDER,
  193. ], null);
  194. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  195. // action
  196. $caughtException = null;
  197. try {
  198. $file->put('test data');
  199. } catch (\Exception $e) {
  200. $caughtException = $e;
  201. }
  202. $this->assertInstanceOf($expectedException, $caughtException);
  203. if ($checkPreviousClass) {
  204. $this->assertInstanceOf(get_class($thrownException), $caughtException->getPrevious());
  205. }
  206. $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files');
  207. }
  208. /**
  209. * Test putting a file using chunking
  210. *
  211. * @dataProvider fopenFailuresProvider
  212. */
  213. public function testChunkedPutFails($thrownException, $expectedException, $checkPreviousClass = false): void {
  214. // setup
  215. $storage = $this->getMockBuilder(Local::class)
  216. ->setMethods(['fopen'])
  217. ->setConstructorArgs([['datadir' => \OC::$server->getTempManager()->getTemporaryFolder()]])
  218. ->getMock();
  219. \OC\Files\Filesystem::mount($storage, [], $this->user . '/');
  220. $view = $this->getMockBuilder(View::class)
  221. ->setMethods(['getRelativePath', 'resolvePath'])
  222. ->getMock();
  223. $view->expects($this->atLeastOnce())
  224. ->method('resolvePath')
  225. ->willReturnCallback(
  226. function ($path) use ($storage) {
  227. return [$storage, $path];
  228. }
  229. );
  230. if ($thrownException !== null) {
  231. $storage->expects($this->once())
  232. ->method('fopen')
  233. ->will($this->throwException($thrownException));
  234. } else {
  235. $storage->expects($this->once())
  236. ->method('fopen')
  237. ->willReturn(false);
  238. }
  239. $view->expects($this->any())
  240. ->method('getRelativePath')
  241. ->willReturnArgument(0);
  242. $request = new Request([
  243. 'server' => [
  244. 'HTTP_OC_CHUNKED' => 'true'
  245. ]
  246. ], $this->requestId, $this->config, null);
  247. $info = new \OC\Files\FileInfo('/test.txt-chunking-12345-2-0', $this->getMockStorage(), null, [
  248. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  249. 'type' => FileInfo::TYPE_FOLDER,
  250. ], null);
  251. $file = new \OCA\DAV\Connector\Sabre\File($view, $info, null, $request);
  252. // put first chunk
  253. $file->acquireLock(ILockingProvider::LOCK_SHARED);
  254. $this->assertNull($file->put('test data one'));
  255. $file->releaseLock(ILockingProvider::LOCK_SHARED);
  256. $info = new \OC\Files\FileInfo('/test.txt-chunking-12345-2-1', $this->getMockStorage(), null, [
  257. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  258. 'type' => FileInfo::TYPE_FOLDER,
  259. ], null);
  260. $file = new \OCA\DAV\Connector\Sabre\File($view, $info, null, $request);
  261. // action
  262. $caughtException = null;
  263. try {
  264. // last chunk
  265. $file->acquireLock(ILockingProvider::LOCK_SHARED);
  266. $file->put('test data two');
  267. $file->releaseLock(ILockingProvider::LOCK_SHARED);
  268. } catch (\Exception $e) {
  269. $caughtException = $e;
  270. }
  271. $this->assertInstanceOf($expectedException, $caughtException);
  272. if ($checkPreviousClass) {
  273. $this->assertInstanceOf(get_class($thrownException), $caughtException->getPrevious());
  274. }
  275. $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files');
  276. }
  277. /**
  278. * Simulate putting a file to the given path.
  279. *
  280. * @param string $path path to put the file into
  281. * @param string $viewRoot root to use for the view
  282. * @param null|Request $request the HTTP request
  283. *
  284. * @return null|string of the PUT operation which is usually the etag
  285. */
  286. private function doPut($path, $viewRoot = null, Request $request = null) {
  287. $view = \OC\Files\Filesystem::getView();
  288. if (!is_null($viewRoot)) {
  289. $view = new \OC\Files\View($viewRoot);
  290. } else {
  291. $viewRoot = '/' . $this->user . '/files';
  292. }
  293. $info = new \OC\Files\FileInfo(
  294. $viewRoot . '/' . ltrim($path, '/'),
  295. $this->getMockStorage(),
  296. null,
  297. [
  298. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  299. 'type' => FileInfo::TYPE_FOLDER,
  300. ],
  301. null
  302. );
  303. /** @var \OCA\DAV\Connector\Sabre\File | MockObject $file */
  304. $file = $this->getMockBuilder(\OCA\DAV\Connector\Sabre\File::class)
  305. ->setConstructorArgs([$view, $info, null, $request])
  306. ->setMethods(['header'])
  307. ->getMock();
  308. // beforeMethod locks
  309. $view->lockFile($path, ILockingProvider::LOCK_SHARED);
  310. $result = $file->put($this->getStream('test data'));
  311. // afterMethod unlocks
  312. $view->unlockFile($path, ILockingProvider::LOCK_SHARED);
  313. return $result;
  314. }
  315. /**
  316. * Test putting a single file
  317. */
  318. public function testPutSingleFile(): void {
  319. $this->assertNotEmpty($this->doPut('/foo.txt'));
  320. }
  321. public function legalMtimeProvider() {
  322. return [
  323. "string" => [
  324. 'HTTP_X_OC_MTIME' => "string",
  325. 'expected result' => null
  326. ],
  327. "castable string (int)" => [
  328. 'HTTP_X_OC_MTIME' => "987654321",
  329. 'expected result' => 987654321
  330. ],
  331. "castable string (float)" => [
  332. 'HTTP_X_OC_MTIME' => "123456789.56",
  333. 'expected result' => 123456789
  334. ],
  335. "float" => [
  336. 'HTTP_X_OC_MTIME' => 123456789.56,
  337. 'expected result' => 123456789
  338. ],
  339. "zero" => [
  340. 'HTTP_X_OC_MTIME' => 0,
  341. 'expected result' => null
  342. ],
  343. "zero string" => [
  344. 'HTTP_X_OC_MTIME' => "0",
  345. 'expected result' => null
  346. ],
  347. "negative zero string" => [
  348. 'HTTP_X_OC_MTIME' => "-0",
  349. 'expected result' => null
  350. ],
  351. "string starting with number following by char" => [
  352. 'HTTP_X_OC_MTIME' => "2345asdf",
  353. 'expected result' => null
  354. ],
  355. "string castable hex int" => [
  356. 'HTTP_X_OC_MTIME' => "0x45adf",
  357. 'expected result' => null
  358. ],
  359. "string that looks like invalid hex int" => [
  360. 'HTTP_X_OC_MTIME' => "0x123g",
  361. 'expected result' => null
  362. ],
  363. "negative int" => [
  364. 'HTTP_X_OC_MTIME' => -34,
  365. 'expected result' => null
  366. ],
  367. "negative float" => [
  368. 'HTTP_X_OC_MTIME' => -34.43,
  369. 'expected result' => null
  370. ],
  371. ];
  372. }
  373. /**
  374. * Test putting a file with string Mtime
  375. * @dataProvider legalMtimeProvider
  376. */
  377. public function testPutSingleFileLegalMtime($requestMtime, $resultMtime): void {
  378. $request = new Request([
  379. 'server' => [
  380. 'HTTP_X_OC_MTIME' => (string)$requestMtime,
  381. ]
  382. ], $this->requestId, $this->config, null);
  383. $file = 'foo.txt';
  384. if ($resultMtime === null) {
  385. $this->expectException(\InvalidArgumentException::class);
  386. }
  387. $this->doPut($file, null, $request);
  388. if ($resultMtime !== null) {
  389. $this->assertEquals($resultMtime, $this->getFileInfos($file)['mtime']);
  390. }
  391. }
  392. /**
  393. * Test putting a file with string Mtime using chunking
  394. * @dataProvider legalMtimeProvider
  395. */
  396. public function testChunkedPutLegalMtime($requestMtime, $resultMtime): void {
  397. $request = new Request([
  398. 'server' => [
  399. 'HTTP_X_OC_MTIME' => (string)$requestMtime,
  400. 'HTTP_OC_CHUNKED' => 'true'
  401. ]
  402. ], $this->requestId, $this->config, null);
  403. $file = 'foo.txt';
  404. if ($resultMtime === null) {
  405. $this->expectException(\Sabre\DAV\Exception::class);
  406. }
  407. $this->doPut($file.'-chunking-12345-2-0', null, $request);
  408. $this->doPut($file.'-chunking-12345-2-1', null, $request);
  409. if ($resultMtime !== null) {
  410. $this->assertEquals($resultMtime, $this->getFileInfos($file)['mtime']);
  411. }
  412. }
  413. /**
  414. * Test putting a file using chunking
  415. */
  416. public function testChunkedPut(): void {
  417. $request = new Request([
  418. 'server' => [
  419. 'HTTP_OC_CHUNKED' => 'true'
  420. ]
  421. ], $this->requestId, $this->config, null);
  422. $this->assertNull($this->doPut('/test.txt-chunking-12345-2-0', null, $request));
  423. $this->assertNotEmpty($this->doPut('/test.txt-chunking-12345-2-1', null, $request));
  424. }
  425. /**
  426. * Test that putting a file triggers create hooks
  427. */
  428. public function testPutSingleFileTriggersHooks(): void {
  429. HookHelper::setUpHooks();
  430. $this->assertNotEmpty($this->doPut('/foo.txt'));
  431. $this->assertCount(4, HookHelper::$hookCalls);
  432. $this->assertHookCall(
  433. HookHelper::$hookCalls[0],
  434. Filesystem::signal_create,
  435. '/foo.txt'
  436. );
  437. $this->assertHookCall(
  438. HookHelper::$hookCalls[1],
  439. Filesystem::signal_write,
  440. '/foo.txt'
  441. );
  442. $this->assertHookCall(
  443. HookHelper::$hookCalls[2],
  444. Filesystem::signal_post_create,
  445. '/foo.txt'
  446. );
  447. $this->assertHookCall(
  448. HookHelper::$hookCalls[3],
  449. Filesystem::signal_post_write,
  450. '/foo.txt'
  451. );
  452. }
  453. /**
  454. * Test that putting a file triggers update hooks
  455. */
  456. public function testPutOverwriteFileTriggersHooks(): void {
  457. $view = \OC\Files\Filesystem::getView();
  458. $view->file_put_contents('/foo.txt', 'some content that will be replaced');
  459. HookHelper::setUpHooks();
  460. $this->assertNotEmpty($this->doPut('/foo.txt'));
  461. $this->assertCount(4, HookHelper::$hookCalls);
  462. $this->assertHookCall(
  463. HookHelper::$hookCalls[0],
  464. Filesystem::signal_update,
  465. '/foo.txt'
  466. );
  467. $this->assertHookCall(
  468. HookHelper::$hookCalls[1],
  469. Filesystem::signal_write,
  470. '/foo.txt'
  471. );
  472. $this->assertHookCall(
  473. HookHelper::$hookCalls[2],
  474. Filesystem::signal_post_update,
  475. '/foo.txt'
  476. );
  477. $this->assertHookCall(
  478. HookHelper::$hookCalls[3],
  479. Filesystem::signal_post_write,
  480. '/foo.txt'
  481. );
  482. }
  483. /**
  484. * Test that putting a file triggers hooks with the correct path
  485. * if the passed view was chrooted (can happen with public webdav
  486. * where the root is the share root)
  487. */
  488. public function testPutSingleFileTriggersHooksDifferentRoot(): void {
  489. $view = \OC\Files\Filesystem::getView();
  490. $view->mkdir('noderoot');
  491. HookHelper::setUpHooks();
  492. // happens with public webdav where the view root is the share root
  493. $this->assertNotEmpty($this->doPut('/foo.txt', '/' . $this->user . '/files/noderoot'));
  494. $this->assertCount(4, HookHelper::$hookCalls);
  495. $this->assertHookCall(
  496. HookHelper::$hookCalls[0],
  497. Filesystem::signal_create,
  498. '/noderoot/foo.txt'
  499. );
  500. $this->assertHookCall(
  501. HookHelper::$hookCalls[1],
  502. Filesystem::signal_write,
  503. '/noderoot/foo.txt'
  504. );
  505. $this->assertHookCall(
  506. HookHelper::$hookCalls[2],
  507. Filesystem::signal_post_create,
  508. '/noderoot/foo.txt'
  509. );
  510. $this->assertHookCall(
  511. HookHelper::$hookCalls[3],
  512. Filesystem::signal_post_write,
  513. '/noderoot/foo.txt'
  514. );
  515. }
  516. /**
  517. * Test that putting a file with chunks triggers create hooks
  518. */
  519. public function testPutChunkedFileTriggersHooks(): void {
  520. HookHelper::setUpHooks();
  521. $request = new Request([
  522. 'server' => [
  523. 'HTTP_OC_CHUNKED' => 'true'
  524. ]
  525. ], $this->requestId, $this->config, null);
  526. $this->assertNull($this->doPut('/foo.txt-chunking-12345-2-0', null, $request));
  527. $this->assertNotEmpty($this->doPut('/foo.txt-chunking-12345-2-1', null, $request));
  528. $this->assertCount(4, HookHelper::$hookCalls);
  529. $this->assertHookCall(
  530. HookHelper::$hookCalls[0],
  531. Filesystem::signal_create,
  532. '/foo.txt'
  533. );
  534. $this->assertHookCall(
  535. HookHelper::$hookCalls[1],
  536. Filesystem::signal_write,
  537. '/foo.txt'
  538. );
  539. $this->assertHookCall(
  540. HookHelper::$hookCalls[2],
  541. Filesystem::signal_post_create,
  542. '/foo.txt'
  543. );
  544. $this->assertHookCall(
  545. HookHelper::$hookCalls[3],
  546. Filesystem::signal_post_write,
  547. '/foo.txt'
  548. );
  549. }
  550. /**
  551. * Test that putting a chunked file triggers update hooks
  552. */
  553. public function testPutOverwriteChunkedFileTriggersHooks(): void {
  554. $view = \OC\Files\Filesystem::getView();
  555. $view->file_put_contents('/foo.txt', 'some content that will be replaced');
  556. HookHelper::setUpHooks();
  557. $request = new Request([
  558. 'server' => [
  559. 'HTTP_OC_CHUNKED' => 'true'
  560. ]
  561. ], $this->requestId, $this->config, null);
  562. $this->assertNull($this->doPut('/foo.txt-chunking-12345-2-0', null, $request));
  563. $this->assertNotEmpty($this->doPut('/foo.txt-chunking-12345-2-1', null, $request));
  564. $this->assertCount(4, HookHelper::$hookCalls);
  565. $this->assertHookCall(
  566. HookHelper::$hookCalls[0],
  567. Filesystem::signal_update,
  568. '/foo.txt'
  569. );
  570. $this->assertHookCall(
  571. HookHelper::$hookCalls[1],
  572. Filesystem::signal_write,
  573. '/foo.txt'
  574. );
  575. $this->assertHookCall(
  576. HookHelper::$hookCalls[2],
  577. Filesystem::signal_post_update,
  578. '/foo.txt'
  579. );
  580. $this->assertHookCall(
  581. HookHelper::$hookCalls[3],
  582. Filesystem::signal_post_write,
  583. '/foo.txt'
  584. );
  585. }
  586. public static function cancellingHook($params): void {
  587. self::$hookCalls[] = [
  588. 'signal' => Filesystem::signal_post_create,
  589. 'params' => $params
  590. ];
  591. }
  592. /**
  593. * Test put file with cancelled hook
  594. */
  595. public function testPutSingleFileCancelPreHook(): void {
  596. \OCP\Util::connectHook(
  597. Filesystem::CLASSNAME,
  598. Filesystem::signal_create,
  599. '\Test\HookHelper',
  600. 'cancellingCallback'
  601. );
  602. // action
  603. $thrown = false;
  604. try {
  605. $this->doPut('/foo.txt');
  606. } catch (\Sabre\DAV\Exception $e) {
  607. $thrown = true;
  608. }
  609. $this->assertTrue($thrown);
  610. $this->assertEmpty($this->listPartFiles(), 'No stray part files');
  611. }
  612. /**
  613. * Test exception when the uploaded size did not match
  614. */
  615. public function testSimplePutFailsSizeCheck(): void {
  616. // setup
  617. $view = $this->getMockBuilder(View::class)
  618. ->setMethods(['rename', 'getRelativePath', 'filesize'])
  619. ->getMock();
  620. $view->expects($this->any())
  621. ->method('rename')
  622. ->withAnyParameters()
  623. ->willReturn(false);
  624. $view->expects($this->any())
  625. ->method('getRelativePath')
  626. ->willReturnArgument(0);
  627. $view->expects($this->any())
  628. ->method('filesize')
  629. ->willReturn(123456);
  630. $request = new Request([
  631. 'server' => [
  632. 'CONTENT_LENGTH' => '123456',
  633. ],
  634. 'method' => 'PUT',
  635. ], $this->requestId, $this->config, null);
  636. $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [
  637. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  638. 'type' => FileInfo::TYPE_FOLDER,
  639. ], null);
  640. $file = new \OCA\DAV\Connector\Sabre\File($view, $info, null, $request);
  641. // action
  642. $thrown = false;
  643. try {
  644. // beforeMethod locks
  645. $file->acquireLock(ILockingProvider::LOCK_SHARED);
  646. $file->put($this->getStream('test data'));
  647. // afterMethod unlocks
  648. $file->releaseLock(ILockingProvider::LOCK_SHARED);
  649. } catch (\Sabre\DAV\Exception\BadRequest $e) {
  650. $thrown = true;
  651. }
  652. $this->assertTrue($thrown);
  653. $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files');
  654. }
  655. /**
  656. * Test exception during final rename in simple upload mode
  657. */
  658. public function testSimplePutFailsMoveFromStorage(): void {
  659. $view = new \OC\Files\View('/' . $this->user . '/files');
  660. // simulate situation where the target file is locked
  661. $view->lockFile('/test.txt', ILockingProvider::LOCK_EXCLUSIVE);
  662. $info = new \OC\Files\FileInfo('/' . $this->user . '/files/test.txt', $this->getMockStorage(), null, [
  663. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  664. 'type' => FileInfo::TYPE_FOLDER,
  665. ], null);
  666. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  667. // action
  668. $thrown = false;
  669. try {
  670. // beforeMethod locks
  671. $view->lockFile($info->getPath(), ILockingProvider::LOCK_SHARED);
  672. $file->put($this->getStream('test data'));
  673. // afterMethod unlocks
  674. $view->unlockFile($info->getPath(), ILockingProvider::LOCK_SHARED);
  675. } catch (\OCA\DAV\Connector\Sabre\Exception\FileLocked $e) {
  676. $thrown = true;
  677. }
  678. $this->assertTrue($thrown);
  679. $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files');
  680. }
  681. /**
  682. * Test exception during final rename in chunk upload mode
  683. */
  684. public function testChunkedPutFailsFinalRename(): void {
  685. $view = new \OC\Files\View('/' . $this->user . '/files');
  686. // simulate situation where the target file is locked
  687. $view->lockFile('/test.txt', ILockingProvider::LOCK_EXCLUSIVE);
  688. $request = new Request([
  689. 'server' => [
  690. 'HTTP_OC_CHUNKED' => 'true'
  691. ]
  692. ], $this->requestId, $this->config, null);
  693. $info = new \OC\Files\FileInfo('/' . $this->user . '/files/test.txt-chunking-12345-2-0', $this->getMockStorage(), null, [
  694. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  695. 'type' => FileInfo::TYPE_FOLDER,
  696. ], null);
  697. $file = new \OCA\DAV\Connector\Sabre\File($view, $info, null, $request);
  698. $file->acquireLock(ILockingProvider::LOCK_SHARED);
  699. $this->assertNull($file->put('test data one'));
  700. $file->releaseLock(ILockingProvider::LOCK_SHARED);
  701. $info = new \OC\Files\FileInfo('/' . $this->user . '/files/test.txt-chunking-12345-2-1', $this->getMockStorage(), null, [
  702. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  703. 'type' => FileInfo::TYPE_FOLDER,
  704. ], null);
  705. $file = new \OCA\DAV\Connector\Sabre\File($view, $info, null, $request);
  706. // action
  707. $thrown = false;
  708. try {
  709. $file->acquireLock(ILockingProvider::LOCK_SHARED);
  710. $file->put($this->getStream('test data'));
  711. $file->releaseLock(ILockingProvider::LOCK_SHARED);
  712. } catch (\OCA\DAV\Connector\Sabre\Exception\FileLocked $e) {
  713. $thrown = true;
  714. }
  715. $this->assertTrue($thrown);
  716. $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files');
  717. }
  718. /**
  719. * Test put file with invalid chars
  720. */
  721. public function testSimplePutInvalidChars(): void {
  722. // setup
  723. $view = $this->getMockBuilder(View::class)
  724. ->setMethods(['getRelativePath'])
  725. ->getMock();
  726. $view->expects($this->any())
  727. ->method('getRelativePath')
  728. ->willReturnArgument(0);
  729. $info = new \OC\Files\FileInfo('/*', $this->getMockStorage(), null, [
  730. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  731. 'type' => FileInfo::TYPE_FOLDER,
  732. ], null);
  733. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  734. // action
  735. $thrown = false;
  736. try {
  737. // beforeMethod locks
  738. $view->lockFile($info->getPath(), ILockingProvider::LOCK_SHARED);
  739. $file->put($this->getStream('test data'));
  740. // afterMethod unlocks
  741. $view->unlockFile($info->getPath(), ILockingProvider::LOCK_SHARED);
  742. } catch (\OCA\DAV\Connector\Sabre\Exception\InvalidPath $e) {
  743. $thrown = true;
  744. }
  745. $this->assertTrue($thrown);
  746. $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files');
  747. }
  748. /**
  749. * Test setting name with setName() with invalid chars
  750. *
  751. */
  752. public function testSetNameInvalidChars(): void {
  753. $this->expectException(\OCA\DAV\Connector\Sabre\Exception\InvalidPath::class);
  754. // setup
  755. $view = $this->getMockBuilder(View::class)
  756. ->setMethods(['getRelativePath'])
  757. ->getMock();
  758. $view->expects($this->any())
  759. ->method('getRelativePath')
  760. ->willReturnArgument(0);
  761. $info = new \OC\Files\FileInfo('/*', $this->getMockStorage(), null, [
  762. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  763. 'type' => FileInfo::TYPE_FOLDER,
  764. ], null);
  765. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  766. $file->setName('/super*star.txt');
  767. }
  768. public function testUploadAbort(): void {
  769. // setup
  770. $view = $this->getMockBuilder(View::class)
  771. ->setMethods(['rename', 'getRelativePath', 'filesize'])
  772. ->getMock();
  773. $view->expects($this->any())
  774. ->method('rename')
  775. ->withAnyParameters()
  776. ->willReturn(false);
  777. $view->expects($this->any())
  778. ->method('getRelativePath')
  779. ->willReturnArgument(0);
  780. $view->expects($this->any())
  781. ->method('filesize')
  782. ->willReturn(123456);
  783. $request = new Request([
  784. 'server' => [
  785. 'CONTENT_LENGTH' => '123456',
  786. ],
  787. 'method' => 'PUT',
  788. ], $this->requestId, $this->config, null);
  789. $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [
  790. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  791. 'type' => FileInfo::TYPE_FOLDER,
  792. ], null);
  793. $file = new \OCA\DAV\Connector\Sabre\File($view, $info, null, $request);
  794. // action
  795. $thrown = false;
  796. try {
  797. // beforeMethod locks
  798. $view->lockFile($info->getPath(), ILockingProvider::LOCK_SHARED);
  799. $file->put($this->getStream('test data'));
  800. // afterMethod unlocks
  801. $view->unlockFile($info->getPath(), ILockingProvider::LOCK_SHARED);
  802. } catch (\Sabre\DAV\Exception\BadRequest $e) {
  803. $thrown = true;
  804. }
  805. $this->assertTrue($thrown);
  806. $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files');
  807. }
  808. public function testDeleteWhenAllowed(): void {
  809. // setup
  810. $view = $this->getMockBuilder(View::class)
  811. ->getMock();
  812. $view->expects($this->once())
  813. ->method('unlink')
  814. ->willReturn(true);
  815. $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [
  816. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  817. 'type' => FileInfo::TYPE_FOLDER,
  818. ], null);
  819. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  820. // action
  821. $file->delete();
  822. }
  823. public function testDeleteThrowsWhenDeletionNotAllowed(): void {
  824. $this->expectException(\Sabre\DAV\Exception\Forbidden::class);
  825. // setup
  826. $view = $this->getMockBuilder(View::class)
  827. ->getMock();
  828. $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [
  829. 'permissions' => 0,
  830. 'type' => FileInfo::TYPE_FOLDER,
  831. ], null);
  832. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  833. // action
  834. $file->delete();
  835. }
  836. public function testDeleteThrowsWhenDeletionFailed(): void {
  837. $this->expectException(\Sabre\DAV\Exception\Forbidden::class);
  838. // setup
  839. $view = $this->getMockBuilder(View::class)
  840. ->getMock();
  841. // but fails
  842. $view->expects($this->once())
  843. ->method('unlink')
  844. ->willReturn(false);
  845. $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [
  846. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  847. 'type' => FileInfo::TYPE_FOLDER,
  848. ], null);
  849. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  850. // action
  851. $file->delete();
  852. }
  853. public function testDeleteThrowsWhenDeletionThrows(): void {
  854. $this->expectException(\OCA\DAV\Connector\Sabre\Exception\Forbidden::class);
  855. // setup
  856. $view = $this->getMockBuilder(View::class)
  857. ->getMock();
  858. // but fails
  859. $view->expects($this->once())
  860. ->method('unlink')
  861. ->willThrowException(new ForbiddenException('', true));
  862. $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [
  863. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  864. 'type' => FileInfo::TYPE_FOLDER,
  865. ], null);
  866. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  867. // action
  868. $file->delete();
  869. }
  870. /**
  871. * Asserts hook call
  872. *
  873. * @param array $callData hook call data to check
  874. * @param string $signal signal name
  875. * @param string $hookPath hook path
  876. */
  877. protected function assertHookCall($callData, $signal, $hookPath) {
  878. $this->assertEquals($signal, $callData['signal']);
  879. $params = $callData['params'];
  880. $this->assertEquals(
  881. $hookPath,
  882. $params[Filesystem::signal_param_path]
  883. );
  884. }
  885. /**
  886. * Test whether locks are set before and after the operation
  887. */
  888. public function testPutLocking(): void {
  889. $view = new \OC\Files\View('/' . $this->user . '/files/');
  890. $path = 'test-locking.txt';
  891. $info = new \OC\Files\FileInfo(
  892. '/' . $this->user . '/files/' . $path,
  893. $this->getMockStorage(),
  894. null,
  895. [
  896. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  897. 'type' => FileInfo::TYPE_FOLDER,
  898. ],
  899. null
  900. );
  901. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  902. $this->assertFalse(
  903. $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_SHARED),
  904. 'File unlocked before put'
  905. );
  906. $this->assertFalse(
  907. $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE),
  908. 'File unlocked before put'
  909. );
  910. $wasLockedPre = false;
  911. $wasLockedPost = false;
  912. $eventHandler = $this->getMockBuilder(\stdclass::class)
  913. ->setMethods(['writeCallback', 'postWriteCallback'])
  914. ->getMock();
  915. // both pre and post hooks might need access to the file,
  916. // so only shared lock is acceptable
  917. $eventHandler->expects($this->once())
  918. ->method('writeCallback')
  919. ->willReturnCallback(
  920. function () use ($view, $path, &$wasLockedPre): void {
  921. $wasLockedPre = $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_SHARED);
  922. $wasLockedPre = $wasLockedPre && !$this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE);
  923. }
  924. );
  925. $eventHandler->expects($this->once())
  926. ->method('postWriteCallback')
  927. ->willReturnCallback(
  928. function () use ($view, $path, &$wasLockedPost): void {
  929. $wasLockedPost = $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_SHARED);
  930. $wasLockedPost = $wasLockedPost && !$this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE);
  931. }
  932. );
  933. \OCP\Util::connectHook(
  934. Filesystem::CLASSNAME,
  935. Filesystem::signal_write,
  936. $eventHandler,
  937. 'writeCallback'
  938. );
  939. \OCP\Util::connectHook(
  940. Filesystem::CLASSNAME,
  941. Filesystem::signal_post_write,
  942. $eventHandler,
  943. 'postWriteCallback'
  944. );
  945. // beforeMethod locks
  946. $view->lockFile($path, ILockingProvider::LOCK_SHARED);
  947. $this->assertNotEmpty($file->put($this->getStream('test data')));
  948. // afterMethod unlocks
  949. $view->unlockFile($path, ILockingProvider::LOCK_SHARED);
  950. $this->assertTrue($wasLockedPre, 'File was locked during pre-hooks');
  951. $this->assertTrue($wasLockedPost, 'File was locked during post-hooks');
  952. $this->assertFalse(
  953. $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_SHARED),
  954. 'File unlocked after put'
  955. );
  956. $this->assertFalse(
  957. $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE),
  958. 'File unlocked after put'
  959. );
  960. }
  961. /**
  962. * Returns part files in the given path
  963. *
  964. * @param \OC\Files\View view which root is the current user's "files" folder
  965. * @param string $path path for which to list part files
  966. *
  967. * @return array list of part files
  968. */
  969. private function listPartFiles(\OC\Files\View $userView = null, $path = '') {
  970. if ($userView === null) {
  971. $userView = \OC\Files\Filesystem::getView();
  972. }
  973. $files = [];
  974. [$storage, $internalPath] = $userView->resolvePath($path);
  975. if ($storage instanceof Local) {
  976. $realPath = $storage->getSourcePath($internalPath);
  977. $dh = opendir($realPath);
  978. while (($file = readdir($dh)) !== false) {
  979. if (substr($file, strlen($file) - 5, 5) === '.part') {
  980. $files[] = $file;
  981. }
  982. }
  983. closedir($dh);
  984. }
  985. return $files;
  986. }
  987. /**
  988. * returns an array of file information filesize, mtime, filetype, mimetype
  989. *
  990. * @param string $path
  991. * @param View $userView
  992. * @return array
  993. */
  994. private function getFileInfos($path = '', View $userView = null) {
  995. if ($userView === null) {
  996. $userView = Filesystem::getView();
  997. }
  998. return [
  999. "filesize" => $userView->filesize($path),
  1000. "mtime" => $userView->filemtime($path),
  1001. "filetype" => $userView->filetype($path),
  1002. "mimetype" => $userView->getMimeType($path)
  1003. ];
  1004. }
  1005. public function testGetFopenFails(): void {
  1006. $this->expectException(\Sabre\DAV\Exception\ServiceUnavailable::class);
  1007. $view = $this->getMockBuilder(View::class)
  1008. ->setMethods(['fopen'])
  1009. ->getMock();
  1010. $view->expects($this->atLeastOnce())
  1011. ->method('fopen')
  1012. ->willReturn(false);
  1013. $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [
  1014. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  1015. 'type' => FileInfo::TYPE_FILE,
  1016. ], null);
  1017. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  1018. $file->get();
  1019. }
  1020. public function testGetFopenThrows(): void {
  1021. $this->expectException(\OCA\DAV\Connector\Sabre\Exception\Forbidden::class);
  1022. $view = $this->getMockBuilder(View::class)
  1023. ->setMethods(['fopen'])
  1024. ->getMock();
  1025. $view->expects($this->atLeastOnce())
  1026. ->method('fopen')
  1027. ->willThrowException(new ForbiddenException('', true));
  1028. $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [
  1029. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  1030. 'type' => FileInfo::TYPE_FILE,
  1031. ], null);
  1032. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  1033. $file->get();
  1034. }
  1035. public function testGetThrowsIfNoPermission(): void {
  1036. $this->expectException(\Sabre\DAV\Exception\NotFound::class);
  1037. $view = $this->getMockBuilder(View::class)
  1038. ->setMethods(['fopen'])
  1039. ->getMock();
  1040. $view->expects($this->never())
  1041. ->method('fopen');
  1042. $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [
  1043. 'permissions' => \OCP\Constants::PERMISSION_CREATE, // no read perm
  1044. 'type' => FileInfo::TYPE_FOLDER,
  1045. ], null);
  1046. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  1047. $file->get();
  1048. }
  1049. public function testSimplePutNoCreatePermissions(): void {
  1050. $this->logout();
  1051. $storage = new Temporary([]);
  1052. $storage->file_put_contents('file.txt', 'old content');
  1053. $noCreateStorage = new PermissionsMask([
  1054. 'storage' => $storage,
  1055. 'mask' => Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE
  1056. ]);
  1057. $this->registerMount($this->user, $noCreateStorage, '/' . $this->user . '/files/root');
  1058. $this->loginAsUser($this->user);
  1059. $view = new View('/' . $this->user . '/files');
  1060. $info = $view->getFileInfo('root/file.txt');
  1061. $file = new File($view, $info);
  1062. // beforeMethod locks
  1063. $view->lockFile('root/file.txt', ILockingProvider::LOCK_SHARED);
  1064. $file->put($this->getStream('new content'));
  1065. // afterMethod unlocks
  1066. $view->unlockFile('root/file.txt', ILockingProvider::LOCK_SHARED);
  1067. $this->assertEquals('new content', $view->file_get_contents('root/file.txt'));
  1068. }
  1069. public function testPutLockExpired(): void {
  1070. $view = new \OC\Files\View('/' . $this->user . '/files/');
  1071. $path = 'test-locking.txt';
  1072. $info = new \OC\Files\FileInfo(
  1073. '/' . $this->user . '/files/' . $path,
  1074. $this->getMockStorage(),
  1075. null,
  1076. [
  1077. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  1078. 'type' => FileInfo::TYPE_FOLDER,
  1079. ],
  1080. null
  1081. );
  1082. $file = new \OCA\DAV\Connector\Sabre\File($view, $info);
  1083. // don't lock before the PUT to simulate an expired shared lock
  1084. $this->assertNotEmpty($file->put($this->getStream('test data')));
  1085. // afterMethod unlocks
  1086. $view->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1087. }
  1088. }