AccessTest.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. * @copyright Copyright (c) 2016, Lukas Reschke <lukas@statuscode.ch>
  5. *
  6. * @author Andreas Fischer <bantu@owncloud.com>
  7. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Roger Szabo <roger.szabo@web.de>
  14. * @author root <root@localhost.localdomain>
  15. * @author Thomas Müller <thomas.mueller@tmit.eu>
  16. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  17. *
  18. * @license AGPL-3.0
  19. *
  20. * This code is free software: you can redistribute it and/or modify
  21. * it under the terms of the GNU Affero General Public License, version 3,
  22. * as published by the Free Software Foundation.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU Affero General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU Affero General Public License, version 3,
  30. * along with this program. If not, see <http://www.gnu.org/licenses/>
  31. *
  32. */
  33. namespace OCA\User_LDAP\Tests;
  34. use OCA\User_LDAP\Access;
  35. use OCA\User_LDAP\Connection;
  36. use OCA\User_LDAP\Exceptions\ConstraintViolationException;
  37. use OCA\User_LDAP\FilesystemHelper;
  38. use OCA\User_LDAP\Helper;
  39. use OCA\User_LDAP\ILDAPWrapper;
  40. use OCA\User_LDAP\LDAP;
  41. use OCA\User_LDAP\LogWrapper;
  42. use OCA\User_LDAP\Mapping\UserMapping;
  43. use OCA\User_LDAP\User\Manager;
  44. use OCA\User_LDAP\User\User;
  45. use OCP\IAvatarManager;
  46. use OCP\IConfig;
  47. use OCP\IDBConnection;
  48. use OCP\Image;
  49. use OCP\IUserManager;
  50. use OCP\Notification\IManager as INotificationManager;
  51. use Test\TestCase;
  52. /**
  53. * Class AccessTest
  54. *
  55. * @group DB
  56. *
  57. * @package OCA\User_LDAP\Tests
  58. */
  59. class AccessTest extends TestCase {
  60. /** @var UserMapping|\PHPUnit_Framework_MockObject_MockObject */
  61. protected $userMapper;
  62. /** @var Connection|\PHPUnit_Framework_MockObject_MockObject */
  63. private $connection;
  64. /** @var LDAP|\PHPUnit_Framework_MockObject_MockObject */
  65. private $ldap;
  66. /** @var Manager|\PHPUnit_Framework_MockObject_MockObject */
  67. private $userManager;
  68. /** @var Helper|\PHPUnit_Framework_MockObject_MockObject */
  69. private $helper;
  70. /** @var IConfig|\PHPUnit_Framework_MockObject_MockObject */
  71. private $config;
  72. /** @var Access */
  73. private $access;
  74. public function setUp() {
  75. $this->connection = $this->createMock(Connection::class);
  76. $this->ldap = $this->createMock(LDAP::class);
  77. $this->userManager = $this->createMock(Manager::class);
  78. $this->helper = $this->createMock(Helper::class);
  79. $this->config = $this->createMock(IConfig::class);
  80. $this->userMapper = $this->createMock(UserMapping::class);
  81. $this->access = new Access(
  82. $this->connection,
  83. $this->ldap,
  84. $this->userManager,
  85. $this->helper,
  86. $this->config
  87. );
  88. $this->access->setUserMapper($this->userMapper);
  89. }
  90. private function getConnectorAndLdapMock() {
  91. $lw = $this->createMock(ILDAPWrapper::class);
  92. $connector = $this->getMockBuilder(Connection::class)
  93. ->setConstructorArgs([$lw, null, null])
  94. ->getMock();
  95. $um = $this->getMockBuilder(Manager::class)
  96. ->setConstructorArgs([
  97. $this->createMock(IConfig::class),
  98. $this->createMock(FilesystemHelper::class),
  99. $this->createMock(LogWrapper::class),
  100. $this->createMock(IAvatarManager::class),
  101. $this->createMock(Image::class),
  102. $this->createMock(IDBConnection::class),
  103. $this->createMock(IUserManager::class),
  104. $this->createMock(INotificationManager::class)])
  105. ->getMock();
  106. $helper = new Helper(\OC::$server->getConfig());
  107. return array($lw, $connector, $um, $helper);
  108. }
  109. public function testEscapeFilterPartValidChars() {
  110. $input = 'okay';
  111. $this->assertTrue($input === $this->access->escapeFilterPart($input));
  112. }
  113. public function testEscapeFilterPartEscapeWildcard() {
  114. $input = '*';
  115. $expected = '\\\\*';
  116. $this->assertTrue($expected === $this->access->escapeFilterPart($input));
  117. }
  118. public function testEscapeFilterPartEscapeWildcard2() {
  119. $input = 'foo*bar';
  120. $expected = 'foo\\\\*bar';
  121. $this->assertTrue($expected === $this->access->escapeFilterPart($input));
  122. }
  123. /**
  124. * @dataProvider convertSID2StrSuccessData
  125. * @param array $sidArray
  126. * @param $sidExpected
  127. */
  128. public function testConvertSID2StrSuccess(array $sidArray, $sidExpected) {
  129. $sidBinary = implode('', $sidArray);
  130. $this->assertSame($sidExpected, $this->access->convertSID2Str($sidBinary));
  131. }
  132. public function convertSID2StrSuccessData() {
  133. return array(
  134. array(
  135. array(
  136. "\x01",
  137. "\x04",
  138. "\x00\x00\x00\x00\x00\x05",
  139. "\x15\x00\x00\x00",
  140. "\xa6\x81\xe5\x0e",
  141. "\x4d\x6c\x6c\x2b",
  142. "\xca\x32\x05\x5f",
  143. ),
  144. 'S-1-5-21-249921958-728525901-1594176202',
  145. ),
  146. array(
  147. array(
  148. "\x01",
  149. "\x02",
  150. "\xFF\xFF\xFF\xFF\xFF\xFF",
  151. "\xFF\xFF\xFF\xFF",
  152. "\xFF\xFF\xFF\xFF",
  153. ),
  154. 'S-1-281474976710655-4294967295-4294967295',
  155. ),
  156. );
  157. }
  158. public function testConvertSID2StrInputError() {
  159. $sidIllegal = 'foobar';
  160. $sidExpected = '';
  161. $this->assertSame($sidExpected, $this->access->convertSID2Str($sidIllegal));
  162. }
  163. public function testGetDomainDNFromDNSuccess() {
  164. $inputDN = 'uid=zaphod,cn=foobar,dc=my,dc=server,dc=com';
  165. $domainDN = 'dc=my,dc=server,dc=com';
  166. $this->ldap->expects($this->once())
  167. ->method('explodeDN')
  168. ->with($inputDN, 0)
  169. ->will($this->returnValue(explode(',', $inputDN)));
  170. $this->assertSame($domainDN, $this->access->getDomainDNFromDN($inputDN));
  171. }
  172. public function testGetDomainDNFromDNError() {
  173. $inputDN = 'foobar';
  174. $expected = '';
  175. $this->ldap->expects($this->once())
  176. ->method('explodeDN')
  177. ->with($inputDN, 0)
  178. ->will($this->returnValue(false));
  179. $this->assertSame($expected, $this->access->getDomainDNFromDN($inputDN));
  180. }
  181. public function dnInputDataProvider() {
  182. return [[
  183. [
  184. 'input' => 'foo=bar,bar=foo,dc=foobar',
  185. 'interResult' => array(
  186. 'count' => 3,
  187. 0 => 'foo=bar',
  188. 1 => 'bar=foo',
  189. 2 => 'dc=foobar'
  190. ),
  191. 'expectedResult' => true
  192. ],
  193. [
  194. 'input' => 'foobarbarfoodcfoobar',
  195. 'interResult' => false,
  196. 'expectedResult' => false
  197. ]
  198. ]];
  199. }
  200. /**
  201. * @dataProvider dnInputDataProvider
  202. * @param array $case
  203. */
  204. public function testStringResemblesDN($case) {
  205. list($lw, $con, $um, $helper) = $this->getConnectorAndLdapMock();
  206. /** @var IConfig|\PHPUnit_Framework_MockObject_MockObject $config */
  207. $config = $this->createMock(IConfig::class);
  208. $access = new Access($con, $lw, $um, $helper, $config);
  209. $lw->expects($this->exactly(1))
  210. ->method('explodeDN')
  211. ->will($this->returnCallback(function ($dn) use ($case) {
  212. if($dn === $case['input']) {
  213. return $case['interResult'];
  214. }
  215. return null;
  216. }));
  217. $this->assertSame($case['expectedResult'], $access->stringResemblesDN($case['input']));
  218. }
  219. /**
  220. * @dataProvider dnInputDataProvider
  221. * @param $case
  222. */
  223. public function testStringResemblesDNLDAPmod($case) {
  224. list(, $con, $um, $helper) = $this->getConnectorAndLdapMock();
  225. /** @var IConfig|\PHPUnit_Framework_MockObject_MockObject $config */
  226. $config = $this->createMock(IConfig::class);
  227. $lw = new LDAP();
  228. $access = new Access($con, $lw, $um, $helper, $config);
  229. if(!function_exists('ldap_explode_dn')) {
  230. $this->markTestSkipped('LDAP Module not available');
  231. }
  232. $this->assertSame($case['expectedResult'], $access->stringResemblesDN($case['input']));
  233. }
  234. public function testCacheUserHome() {
  235. $this->connection->expects($this->once())
  236. ->method('writeToCache');
  237. $this->access->cacheUserHome('foobar', '/foobars/path');
  238. }
  239. public function testBatchApplyUserAttributes() {
  240. $this->ldap->expects($this->any())
  241. ->method('isResource')
  242. ->willReturn(true);
  243. $this->ldap->expects($this->any())
  244. ->method('getAttributes')
  245. ->willReturn(['displayname' => ['bar', 'count' => 1]]);
  246. /** @var UserMapping|\PHPUnit_Framework_MockObject_MockObject $mapperMock */
  247. $mapperMock = $this->createMock(UserMapping::class);
  248. $mapperMock->expects($this->any())
  249. ->method('getNameByDN')
  250. ->willReturn(false);
  251. $mapperMock->expects($this->any())
  252. ->method('map')
  253. ->willReturn(true);
  254. $userMock = $this->createMock(User::class);
  255. // also returns for userUuidAttribute
  256. $this->access->connection->expects($this->any())
  257. ->method('__get')
  258. ->will($this->returnValue('displayName'));
  259. $this->access->setUserMapper($mapperMock);
  260. $displayNameAttribute = strtolower($this->access->connection->ldapUserDisplayName);
  261. $data = [
  262. [
  263. 'dn' => ['foobar'],
  264. $displayNameAttribute => 'barfoo'
  265. ],
  266. [
  267. 'dn' => ['foo'],
  268. $displayNameAttribute => 'bar'
  269. ],
  270. [
  271. 'dn' => ['raboof'],
  272. $displayNameAttribute => 'oofrab'
  273. ]
  274. ];
  275. $userMock->expects($this->exactly(count($data)))
  276. ->method('processAttributes');
  277. $this->userManager->expects($this->exactly(count($data)))
  278. ->method('get')
  279. ->will($this->returnValue($userMock));
  280. $this->access->batchApplyUserAttributes($data);
  281. }
  282. public function testBatchApplyUserAttributesSkipped() {
  283. /** @var UserMapping|\PHPUnit_Framework_MockObject_MockObject $mapperMock */
  284. $mapperMock = $this->createMock(UserMapping::class);
  285. $mapperMock->expects($this->any())
  286. ->method('getNameByDN')
  287. ->will($this->returnValue('a_username'));
  288. $userMock = $this->createMock(User::class);
  289. $this->access->connection->expects($this->any())
  290. ->method('__get')
  291. ->will($this->returnValue('displayName'));
  292. $this->access->setUserMapper($mapperMock);
  293. $displayNameAttribute = strtolower($this->access->connection->ldapUserDisplayName);
  294. $data = [
  295. [
  296. 'dn' => ['foobar'],
  297. $displayNameAttribute => 'barfoo'
  298. ],
  299. [
  300. 'dn' => ['foo'],
  301. $displayNameAttribute => 'bar'
  302. ],
  303. [
  304. 'dn' => ['raboof'],
  305. $displayNameAttribute => 'oofrab'
  306. ]
  307. ];
  308. $userMock->expects($this->never())
  309. ->method('processAttributes');
  310. $this->userManager->expects($this->any())
  311. ->method('get')
  312. ->willReturn($this->createMock(User::class));
  313. $this->access->batchApplyUserAttributes($data);
  314. }
  315. public function testBatchApplyUserAttributesDontSkip() {
  316. /** @var UserMapping|\PHPUnit_Framework_MockObject_MockObject $mapperMock */
  317. $mapperMock = $this->createMock(UserMapping::class);
  318. $mapperMock->expects($this->any())
  319. ->method('getNameByDN')
  320. ->will($this->returnValue('a_username'));
  321. $userMock = $this->createMock(User::class);
  322. $this->access->connection->expects($this->any())
  323. ->method('__get')
  324. ->will($this->returnValue('displayName'));
  325. $this->access->setUserMapper($mapperMock);
  326. $displayNameAttribute = strtolower($this->access->connection->ldapUserDisplayName);
  327. $data = [
  328. [
  329. 'dn' => ['foobar'],
  330. $displayNameAttribute => 'barfoo'
  331. ],
  332. [
  333. 'dn' => ['foo'],
  334. $displayNameAttribute => 'bar'
  335. ],
  336. [
  337. 'dn' => ['raboof'],
  338. $displayNameAttribute => 'oofrab'
  339. ]
  340. ];
  341. $userMock->expects($this->exactly(count($data)))
  342. ->method('processAttributes');
  343. $this->userManager->expects($this->exactly(count($data)))
  344. ->method('get')
  345. ->will($this->returnValue($userMock));
  346. $this->access->batchApplyUserAttributes($data);
  347. }
  348. public function dNAttributeProvider() {
  349. // corresponds to Access::resemblesDN()
  350. return array(
  351. 'dn' => array('dn'),
  352. 'uniqueMember' => array('uniquemember'),
  353. 'member' => array('member'),
  354. 'memberOf' => array('memberof')
  355. );
  356. }
  357. /**
  358. * @dataProvider dNAttributeProvider
  359. * @param $attribute
  360. */
  361. public function testSanitizeDN($attribute) {
  362. list($lw, $con, $um, $helper) = $this->getConnectorAndLdapMock();
  363. /** @var IConfig|\PHPUnit_Framework_MockObject_MockObject $config */
  364. $config = $this->createMock(IConfig::class);
  365. $dnFromServer = 'cn=Mixed Cases,ou=Are Sufficient To,ou=Test,dc=example,dc=org';
  366. $lw->expects($this->any())
  367. ->method('isResource')
  368. ->will($this->returnValue(true));
  369. $lw->expects($this->any())
  370. ->method('getAttributes')
  371. ->will($this->returnValue(array(
  372. $attribute => array('count' => 1, $dnFromServer)
  373. )));
  374. $access = new Access($con, $lw, $um, $helper, $config);
  375. $values = $access->readAttribute('uid=whoever,dc=example,dc=org', $attribute);
  376. $this->assertSame($values[0], strtolower($dnFromServer));
  377. }
  378. /**
  379. * @expectedException \Exception
  380. * @expectedExceptionMessage LDAP password changes are disabled
  381. */
  382. public function testSetPasswordWithDisabledChanges() {
  383. $this->connection
  384. ->method('__get')
  385. ->willReturn(false);
  386. /** @noinspection PhpUnhandledExceptionInspection */
  387. $this->access->setPassword('CN=foo', 'MyPassword');
  388. }
  389. public function testSetPasswordWithLdapNotAvailable() {
  390. $this->connection
  391. ->method('__get')
  392. ->willReturn(true);
  393. $connection = $this->createMock(LDAP::class);
  394. $this->connection
  395. ->expects($this->once())
  396. ->method('getConnectionResource')
  397. ->willReturn($connection);
  398. $this->ldap
  399. ->expects($this->once())
  400. ->method('isResource')
  401. ->with($connection)
  402. ->willReturn(false);
  403. /** @noinspection PhpUnhandledExceptionInspection */
  404. $this->assertFalse($this->access->setPassword('CN=foo', 'MyPassword'));
  405. }
  406. /**
  407. * @expectedException \OC\HintException
  408. * @expectedExceptionMessage Password change rejected.
  409. */
  410. public function testSetPasswordWithRejectedChange() {
  411. $this->connection
  412. ->method('__get')
  413. ->willReturn(true);
  414. $connection = $this->createMock(LDAP::class);
  415. $this->connection
  416. ->expects($this->once())
  417. ->method('getConnectionResource')
  418. ->willReturn($connection);
  419. $this->ldap
  420. ->expects($this->once())
  421. ->method('isResource')
  422. ->with($connection)
  423. ->willReturn(true);
  424. $this->ldap
  425. ->expects($this->once())
  426. ->method('modReplace')
  427. ->with($connection, 'CN=foo', 'MyPassword')
  428. ->willThrowException(new ConstraintViolationException());
  429. /** @noinspection PhpUnhandledExceptionInspection */
  430. $this->access->setPassword('CN=foo', 'MyPassword');
  431. }
  432. public function testSetPassword() {
  433. $this->connection
  434. ->method('__get')
  435. ->willReturn(true);
  436. $connection = $this->createMock(LDAP::class);
  437. $this->connection
  438. ->expects($this->once())
  439. ->method('getConnectionResource')
  440. ->willReturn($connection);
  441. $this->ldap
  442. ->expects($this->once())
  443. ->method('isResource')
  444. ->with($connection)
  445. ->willReturn(true);
  446. $this->ldap
  447. ->expects($this->once())
  448. ->method('modReplace')
  449. ->with($connection, 'CN=foo', 'MyPassword')
  450. ->willReturn(true);
  451. /** @noinspection PhpUnhandledExceptionInspection */
  452. $this->assertTrue($this->access->setPassword('CN=foo', 'MyPassword'));
  453. }
  454. protected function prepareMocksForSearchTests(
  455. $base,
  456. $fakeConnection,
  457. $fakeSearchResultResource,
  458. $fakeLdapEntries
  459. ) {
  460. $this->connection
  461. ->expects($this->any())
  462. ->method('getConnectionResource')
  463. ->willReturn($fakeConnection);
  464. $this->connection->expects($this->any())
  465. ->method('__get')
  466. ->willReturnCallback(function($key) use ($base) {
  467. if(stripos($key, 'base') !== false) {
  468. return $base;
  469. }
  470. return null;
  471. });
  472. $this->ldap
  473. ->expects($this->any())
  474. ->method('isResource')
  475. ->willReturnCallback(function ($resource) use ($fakeConnection) {
  476. return $resource === $fakeConnection;
  477. });
  478. $this->ldap
  479. ->expects($this->any())
  480. ->method('errno')
  481. ->willReturn(0);
  482. $this->ldap
  483. ->expects($this->once())
  484. ->method('search')
  485. ->willReturn([$fakeSearchResultResource]);
  486. $this->ldap
  487. ->expects($this->exactly(count($base)))
  488. ->method('getEntries')
  489. ->willReturn($fakeLdapEntries);
  490. $this->helper->expects($this->any())
  491. ->method('sanitizeDN')
  492. ->willReturnArgument(0);
  493. }
  494. public function testSearchNoPagedSearch() {
  495. // scenario: no pages search, 1 search base
  496. $filter = 'objectClass=nextcloudUser';
  497. $base = ['ou=zombies,dc=foobar,dc=nextcloud,dc=com'];
  498. $fakeConnection = new \stdClass();
  499. $fakeSearchResultResource = new \stdClass();
  500. $fakeLdapEntries = [
  501. 'count' => 2,
  502. [
  503. 'dn' => 'uid=sgarth,' . $base[0],
  504. ],
  505. [
  506. 'dn' => 'uid=wwilson,' . $base[0],
  507. ]
  508. ];
  509. $expected = $fakeLdapEntries;
  510. unset($expected['count']);
  511. $this->prepareMocksForSearchTests($base, $fakeConnection, $fakeSearchResultResource, $fakeLdapEntries);
  512. /** @noinspection PhpUnhandledExceptionInspection */
  513. $result = $this->access->search($filter, $base);
  514. $this->assertSame($expected, $result);
  515. }
  516. public function testFetchListOfUsers() {
  517. $filter = 'objectClass=nextcloudUser';
  518. $base = ['ou=zombies,dc=foobar,dc=nextcloud,dc=com'];
  519. $attrs = ['dn', 'uid'];
  520. $fakeConnection = new \stdClass();
  521. $fakeSearchResultResource = new \stdClass();
  522. $fakeLdapEntries = [
  523. 'count' => 2,
  524. [
  525. 'dn' => 'uid=sgarth,' . $base[0],
  526. 'uid' => [ 'sgarth' ],
  527. ],
  528. [
  529. 'dn' => 'uid=wwilson,' . $base[0],
  530. 'uid' => [ 'wwilson' ],
  531. ]
  532. ];
  533. $expected = $fakeLdapEntries;
  534. unset($expected['count']);
  535. array_walk($expected, function(&$v) {
  536. $v['dn'] = [$v['dn']]; // dn is translated into an array internally for consistency
  537. });
  538. $this->prepareMocksForSearchTests($base, $fakeConnection, $fakeSearchResultResource, $fakeLdapEntries);
  539. $this->connection->expects($this->exactly($fakeLdapEntries['count']))
  540. ->method('writeToCache')
  541. ->with($this->stringStartsWith('userExists'), true);
  542. $this->userMapper->expects($this->exactly($fakeLdapEntries['count']))
  543. ->method('getNameByDN')
  544. ->willReturnCallback(function($fdn) {
  545. $parts = ldap_explode_dn($fdn, false);
  546. return $parts[0];
  547. });
  548. /** @noinspection PhpUnhandledExceptionInspection */
  549. $list = $this->access->fetchListOfUsers($filter, $attrs);
  550. $this->assertSame($expected, $list);
  551. }
  552. }