DefaultTokenProviderTest.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. <?php
  2. /**
  3. * @author Christoph Wurst <christoph@owncloud.com>
  4. *
  5. * @copyright Copyright (c) 2016, Lukas Reschke <lukas@statuscode.ch>
  6. * @copyright Copyright (c) 2016, ownCloud, Inc.
  7. * @license AGPL-3.0
  8. *
  9. * This code is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU Affero General Public License, version 3,
  11. * as published by the Free Software Foundation.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU Affero General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public License, version 3,
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>
  20. *
  21. */
  22. namespace Test\Authentication\Token;
  23. use OC\Authentication\Exceptions\ExpiredTokenException;
  24. use OC\Authentication\Exceptions\InvalidTokenException;
  25. use OC\Authentication\Token\DefaultToken;
  26. use OC\Authentication\Token\DefaultTokenMapper;
  27. use OC\Authentication\Token\DefaultTokenProvider;
  28. use OC\Authentication\Token\IToken;
  29. use OC\Authentication\Token\PublicKeyToken;
  30. use OCP\AppFramework\Db\DoesNotExistException;
  31. use OCP\AppFramework\Utility\ITimeFactory;
  32. use OCP\IConfig;
  33. use OCP\ILogger;
  34. use OCP\Security\ICrypto;
  35. use Test\TestCase;
  36. class DefaultTokenProviderTest extends TestCase {
  37. /** @var DefaultTokenProvider|\PHPUnit_Framework_MockObject_MockObject */
  38. private $tokenProvider;
  39. /** @var DefaultTokenMapper|\PHPUnit_Framework_MockObject_MockObject */
  40. private $mapper;
  41. /** @var ICrypto|\PHPUnit_Framework_MockObject_MockObject */
  42. private $crypto;
  43. /** @var IConfig|\PHPUnit_Framework_MockObject_MockObject */
  44. private $config;
  45. /** @var ILogger|\PHPUnit_Framework_MockObject_MockObject */
  46. private $logger;
  47. /** @var ITimeFactory|\PHPUnit_Framework_MockObject_MockObject */
  48. private $timeFactory;
  49. /** @var int */
  50. private $time;
  51. protected function setUp() {
  52. parent::setUp();
  53. $this->mapper = $this->createMock(DefaultTokenMapper::class);
  54. $this->crypto = $this->createMock(ICrypto::class);
  55. $this->config = $this->createMock(IConfig::class);
  56. $this->logger = $this->createMock(ILogger::class);
  57. $this->timeFactory = $this->createMock(ITimeFactory::class);
  58. $this->time = 1313131;
  59. $this->timeFactory->expects($this->any())
  60. ->method('getTime')
  61. ->will($this->returnValue($this->time));
  62. $this->tokenProvider = new DefaultTokenProvider($this->mapper, $this->crypto, $this->config, $this->logger,
  63. $this->timeFactory);
  64. }
  65. public function testGenerateToken() {
  66. $token = 'token';
  67. $uid = 'user';
  68. $user = 'User';
  69. $password = 'passme';
  70. $name = 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12'
  71. . 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12'
  72. . 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12'
  73. . 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12';
  74. $type = IToken::PERMANENT_TOKEN;
  75. $toInsert = new DefaultToken();
  76. $toInsert->setUid($uid);
  77. $toInsert->setLoginName($user);
  78. $toInsert->setPassword('encryptedpassword');
  79. $toInsert->setName($name);
  80. $toInsert->setToken(hash('sha512', $token . '1f4h9s'));
  81. $toInsert->setType($type);
  82. $toInsert->setRemember(IToken::DO_NOT_REMEMBER);
  83. $toInsert->setLastActivity($this->time);
  84. $toInsert->setLastCheck($this->time);
  85. $toInsert->setVersion(DefaultToken::VERSION);
  86. $this->config->expects($this->any())
  87. ->method('getSystemValue')
  88. ->with('secret')
  89. ->will($this->returnValue('1f4h9s'));
  90. $this->crypto->expects($this->once())
  91. ->method('encrypt')
  92. ->with($password, $token . '1f4h9s')
  93. ->will($this->returnValue('encryptedpassword'));
  94. $this->mapper->expects($this->once())
  95. ->method('insert')
  96. ->with($this->equalTo($toInsert));
  97. $actual = $this->tokenProvider->generateToken($token, $uid, $user, $password, $name, $type, IToken::DO_NOT_REMEMBER);
  98. $this->assertEquals($toInsert, $actual);
  99. }
  100. public function testUpdateToken() {
  101. $tk = new DefaultToken();
  102. $tk->setLastActivity($this->time - 200);
  103. $this->mapper->expects($this->once())
  104. ->method('update')
  105. ->with($tk);
  106. $this->tokenProvider->updateTokenActivity($tk);
  107. $this->assertEquals($this->time, $tk->getLastActivity());
  108. }
  109. public function testUpdateTokenDebounce() {
  110. $tk = new DefaultToken();
  111. $tk->setLastActivity($this->time - 30);
  112. $this->mapper->expects($this->never())
  113. ->method('update')
  114. ->with($tk);
  115. $this->tokenProvider->updateTokenActivity($tk);
  116. }
  117. public function testGetTokenByUser() {
  118. $this->mapper->expects($this->once())
  119. ->method('getTokenByUser')
  120. ->with('uid')
  121. ->will($this->returnValue(['token']));
  122. $this->assertEquals(['token'], $this->tokenProvider->getTokenByUser('uid'));
  123. }
  124. public function testGetPassword() {
  125. $token = 'token1234';
  126. $tk = new DefaultToken();
  127. $tk->setPassword('someencryptedvalue');
  128. $this->config->expects($this->once())
  129. ->method('getSystemValue')
  130. ->with('secret')
  131. ->will($this->returnValue('1f4h9s'));
  132. $this->crypto->expects($this->once())
  133. ->method('decrypt')
  134. ->with('someencryptedvalue', $token . '1f4h9s')
  135. ->will($this->returnValue('passme'));
  136. $actual = $this->tokenProvider->getPassword($tk, $token);
  137. $this->assertEquals('passme', $actual);
  138. }
  139. /**
  140. * @expectedException \OC\Authentication\Exceptions\PasswordlessTokenException
  141. */
  142. public function testGetPasswordPasswordLessToken() {
  143. $token = 'token1234';
  144. $tk = new DefaultToken();
  145. $tk->setPassword(null);
  146. $this->tokenProvider->getPassword($tk, $token);
  147. }
  148. /**
  149. * @expectedException \OC\Authentication\Exceptions\InvalidTokenException
  150. */
  151. public function testGetPasswordDeletesInvalidToken() {
  152. $token = 'token1234';
  153. $tk = new DefaultToken();
  154. $tk->setPassword('someencryptedvalue');
  155. /* @var $tokenProvider DefaultTokenProvider */
  156. $tokenProvider = $this->getMockBuilder('\OC\Authentication\Token\DefaultTokenProvider')
  157. ->setMethods([
  158. 'invalidateToken'
  159. ])
  160. ->setConstructorArgs([$this->mapper, $this->crypto, $this->config, $this->logger,
  161. $this->timeFactory])
  162. ->getMock();
  163. $this->config->expects($this->once())
  164. ->method('getSystemValue')
  165. ->with('secret')
  166. ->will($this->returnValue('1f4h9s'));
  167. $this->crypto->expects($this->once())
  168. ->method('decrypt')
  169. ->with('someencryptedvalue', $token . '1f4h9s')
  170. ->will($this->throwException(new \Exception('some crypto error occurred')));
  171. $tokenProvider->expects($this->once())
  172. ->method('invalidateToken')
  173. ->with($token);
  174. $tokenProvider->getPassword($tk, $token);
  175. }
  176. public function testSetPassword() {
  177. $token = new DefaultToken();
  178. $tokenId = 'token123';
  179. $password = '123456';
  180. $this->config->expects($this->once())
  181. ->method('getSystemValue')
  182. ->with('secret')
  183. ->will($this->returnValue('ocsecret'));
  184. $this->crypto->expects($this->once())
  185. ->method('encrypt')
  186. ->with($password, $tokenId . 'ocsecret')
  187. ->will($this->returnValue('encryptedpassword'));
  188. $this->mapper->expects($this->once())
  189. ->method('update')
  190. ->with($token);
  191. $this->tokenProvider->setPassword($token, $tokenId, $password);
  192. $this->assertEquals('encryptedpassword', $token->getPassword());
  193. }
  194. /**
  195. * @expectedException \OC\Authentication\Exceptions\InvalidTokenException
  196. */
  197. public function testSetPasswordInvalidToken() {
  198. $token = $this->createMock(IToken::class);
  199. $tokenId = 'token123';
  200. $password = '123456';
  201. $this->tokenProvider->setPassword($token, $tokenId, $password);
  202. }
  203. public function testInvalidateToken() {
  204. $this->mapper->expects($this->once())
  205. ->method('invalidate')
  206. ->with(hash('sha512', 'token7'));
  207. $this->tokenProvider->invalidateToken('token7');
  208. }
  209. public function testInvaildateTokenById() {
  210. $id = 123;
  211. $this->mapper->expects($this->once())
  212. ->method('deleteById')
  213. ->with('uid', $id);
  214. $this->tokenProvider->invalidateTokenById('uid', $id);
  215. }
  216. public function testInvalidateOldTokens() {
  217. $defaultSessionLifetime = 60 * 60 * 24;
  218. $defaultRememberMeLifetime = 60 * 60 * 24 * 15;
  219. $this->config->expects($this->exactly(2))
  220. ->method('getSystemValue')
  221. ->will($this->returnValueMap([
  222. ['session_lifetime', $defaultSessionLifetime, 150],
  223. ['remember_login_cookie_lifetime', $defaultRememberMeLifetime, 300],
  224. ]));
  225. $this->mapper->expects($this->at(0))
  226. ->method('invalidateOld')
  227. ->with($this->time - 150);
  228. $this->mapper->expects($this->at(1))
  229. ->method('invalidateOld')
  230. ->with($this->time - 300);
  231. $this->tokenProvider->invalidateOldTokens();
  232. }
  233. public function testRenewSessionTokenWithoutPassword() {
  234. $token = $this->getMockBuilder(DefaultToken::class)
  235. ->disableOriginalConstructor()
  236. ->setMethods(['getUID', 'getLoginName', 'getPassword', 'getName', 'getRemember'])
  237. ->getMock();
  238. $token
  239. ->expects($this->at(0))
  240. ->method('getUID')
  241. ->willReturn('UserUid');
  242. $token
  243. ->expects($this->at(1))
  244. ->method('getLoginName')
  245. ->willReturn('UserLoginName');
  246. $token
  247. ->expects($this->at(2))
  248. ->method('getPassword')
  249. ->willReturn(null);
  250. $token
  251. ->expects($this->at(3))
  252. ->method('getName')
  253. ->willReturn('MyTokenName');
  254. $token
  255. ->expects($this->at(4))
  256. ->method('getRemember')
  257. ->willReturn(IToken::DO_NOT_REMEMBER);
  258. $this->config
  259. ->expects($this->exactly(2))
  260. ->method('getSystemValue')
  261. ->with('secret')
  262. ->willReturn('MyInstanceSecret');
  263. $this->mapper
  264. ->expects($this->at(0))
  265. ->method('getToken')
  266. ->with(hash('sha512', 'oldId' . 'MyInstanceSecret'))
  267. ->willReturn($token);
  268. $newToken = new DefaultToken();
  269. $newToken->setUid('UserUid');
  270. $newToken->setLoginName('UserLoginName');
  271. $newToken->setName('MyTokenName');
  272. $newToken->setToken(hash('sha512', 'newId' . 'MyInstanceSecret'));
  273. $newToken->setType(IToken::TEMPORARY_TOKEN);
  274. $newToken->setRemember(IToken::DO_NOT_REMEMBER);
  275. $newToken->setLastActivity(1313131);
  276. $this->mapper
  277. ->expects($this->at(1))
  278. ->method('insert')
  279. ->with($newToken);
  280. $this->mapper
  281. ->expects($this->at(2))
  282. ->method('delete')
  283. ->with($token);
  284. $this->tokenProvider->renewSessionToken('oldId', 'newId');
  285. }
  286. public function testRenewSessionTokenWithPassword() {
  287. $token = $this->getMockBuilder(DefaultToken::class)
  288. ->disableOriginalConstructor()
  289. ->setMethods(['getUID', 'getLoginName', 'getPassword', 'getName', 'getRemember'])
  290. ->getMock();
  291. $token
  292. ->expects($this->at(0))
  293. ->method('getUID')
  294. ->willReturn('UserUid');
  295. $token
  296. ->expects($this->at(1))
  297. ->method('getLoginName')
  298. ->willReturn('UserLoginName');
  299. $token
  300. ->expects($this->at(2))
  301. ->method('getPassword')
  302. ->willReturn('EncryptedPassword');
  303. $token
  304. ->expects($this->at(3))
  305. ->method('getPassword')
  306. ->willReturn('EncryptedPassword');
  307. $token
  308. ->expects($this->at(4))
  309. ->method('getName')
  310. ->willReturn('MyTokenName');
  311. $token
  312. ->expects($this->at(5))
  313. ->method('getRemember')
  314. ->willReturn(IToken::REMEMBER);
  315. $this->crypto
  316. ->expects($this->any(0))
  317. ->method('decrypt')
  318. ->with('EncryptedPassword', 'oldIdMyInstanceSecret')
  319. ->willReturn('ClearTextPassword');
  320. $this->crypto
  321. ->expects($this->any(1))
  322. ->method('encrypt')
  323. ->with('ClearTextPassword', 'newIdMyInstanceSecret')
  324. ->willReturn('EncryptedPassword');
  325. $this->config
  326. ->expects($this->exactly(4))
  327. ->method('getSystemValue')
  328. ->with('secret')
  329. ->willReturn('MyInstanceSecret');
  330. $this->mapper
  331. ->expects($this->at(0))
  332. ->method('getToken')
  333. ->with(hash('sha512', 'oldId' . 'MyInstanceSecret'))
  334. ->willReturn($token);
  335. $newToken = new DefaultToken();
  336. $newToken->setUid('UserUid');
  337. $newToken->setLoginName('UserLoginName');
  338. $newToken->setName('MyTokenName');
  339. $newToken->setToken(hash('sha512', 'newId' . 'MyInstanceSecret'));
  340. $newToken->setType(IToken::TEMPORARY_TOKEN);
  341. $newToken->setRemember(IToken::REMEMBER);
  342. $newToken->setLastActivity(1313131);
  343. $newToken->setPassword('EncryptedPassword');
  344. $this->mapper
  345. ->expects($this->at(1))
  346. ->method('insert')
  347. ->with($this->equalTo($newToken));
  348. $this->mapper
  349. ->expects($this->at(2))
  350. ->method('delete')
  351. ->with($token);
  352. $this->tokenProvider->renewSessionToken('oldId', 'newId');
  353. }
  354. public function testGetToken() {
  355. $token = new DefaultToken();
  356. $this->config->method('getSystemValue')
  357. ->with('secret')
  358. ->willReturn('mysecret');
  359. $this->mapper->method('getToken')
  360. ->with(
  361. $this->callback(function (string $token) {
  362. return hash('sha512', 'unhashedTokenmysecret') === $token;
  363. })
  364. )->willReturn($token);
  365. $this->assertSame($token, $this->tokenProvider->getToken('unhashedToken'));
  366. }
  367. public function testGetInvalidToken() {
  368. $this->expectException(InvalidTokenException::class);
  369. $this->config->method('getSystemValue')
  370. ->with('secret')
  371. ->willReturn('mysecret');
  372. $this->mapper->method('getToken')
  373. ->with(
  374. $this->callback(function (string $token) {
  375. return hash('sha512', 'unhashedTokenmysecret') === $token;
  376. })
  377. )->willThrowException(new InvalidTokenException());
  378. $this->tokenProvider->getToken('unhashedToken');
  379. }
  380. public function testGetExpiredToken() {
  381. $token = new DefaultToken();
  382. $token->setExpires(42);
  383. $this->config->method('getSystemValue')
  384. ->with('secret')
  385. ->willReturn('mysecret');
  386. $this->mapper->method('getToken')
  387. ->with(
  388. $this->callback(function (string $token) {
  389. return hash('sha512', 'unhashedTokenmysecret') === $token;
  390. })
  391. )->willReturn($token);
  392. try {
  393. $this->tokenProvider->getToken('unhashedToken');
  394. } catch (ExpiredTokenException $e) {
  395. $this->assertSame($token, $e->getToken());
  396. }
  397. }
  398. public function testGetTokenById() {
  399. $token = $this->createMock(DefaultToken::class);
  400. $this->mapper->expects($this->once())
  401. ->method('getTokenById')
  402. ->with($this->equalTo(42))
  403. ->willReturn($token);
  404. $this->assertSame($token, $this->tokenProvider->getTokenById(42));
  405. }
  406. public function testGetInvalidTokenById() {
  407. $this->expectException(InvalidTokenException::class);
  408. $this->mapper->expects($this->once())
  409. ->method('getTokenById')
  410. ->with($this->equalTo(42))
  411. ->willThrowException(new DoesNotExistException('nope'));
  412. $this->tokenProvider->getTokenById(42);
  413. }
  414. public function testGetExpiredTokenById() {
  415. $token = new DefaultToken();
  416. $token->setExpires(42);
  417. $this->mapper->expects($this->once())
  418. ->method('getTokenById')
  419. ->with($this->equalTo(42))
  420. ->willReturn($token);
  421. try {
  422. $this->tokenProvider->getTokenById(42);
  423. $this->fail();
  424. } catch (ExpiredTokenException $e) {
  425. $this->assertSame($token, $e->getToken());
  426. }
  427. }
  428. public function testRotate() {
  429. $token = new DefaultToken();
  430. $token->setPassword('oldencryptedpassword');
  431. $this->config->method('getSystemValue')
  432. ->with('secret')
  433. ->willReturn('mysecret');
  434. $this->crypto->method('decrypt')
  435. ->with('oldencryptedpassword', 'oldtokenmysecret')
  436. ->willReturn('mypassword');
  437. $this->crypto->method('encrypt')
  438. ->with('mypassword', 'newtokenmysecret')
  439. ->willReturn('newencryptedpassword');
  440. $this->mapper->expects($this->once())
  441. ->method('update')
  442. ->with($this->callback(function (DefaultToken $token) {
  443. return $token->getPassword() === 'newencryptedpassword' &&
  444. $token->getToken() === hash('sha512', 'newtokenmysecret');
  445. }));
  446. $this->tokenProvider->rotate($token, 'oldtoken', 'newtoken');
  447. }
  448. public function testRotateNoPassword() {
  449. $token = new DefaultToken();
  450. $this->config->method('getSystemValue')
  451. ->with('secret')
  452. ->willReturn('mysecret');
  453. $this->mapper->expects($this->once())
  454. ->method('update')
  455. ->with($this->callback(function (DefaultToken $token) {
  456. return $token->getPassword() === null &&
  457. $token->getToken() === hash('sha512', 'newtokenmysecret');
  458. }));
  459. $this->tokenProvider->rotate($token, 'oldtoken', 'newtoken');
  460. }
  461. public function testMarkPasswordInvalidInvalidToken() {
  462. $token = $this->createMock(PublicKeyToken::class);
  463. $this->expectException(InvalidTokenException::class);
  464. $this->tokenProvider->markPasswordInvalid($token, 'tokenId');
  465. }
  466. public function testMarkPasswordInvalid() {
  467. $token = $this->createMock(DefaultToken::class);
  468. $this->mapper->expects($this->once())
  469. ->method('invalidate')
  470. ->with('0c7db0098fe8ddba6032b22719ec18867c69a1820fa36d71c28bf96d52843bdc44a112bd24093b049be5bb54769bcb72d67190a4a9690e51aac263cba38186fb');
  471. $this->tokenProvider->markPasswordInvalid($token, 'tokenId');
  472. }
  473. }