1
0

SessionTest.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157
  1. <?php
  2. /**
  3. * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com>
  4. * This file is licensed under the Affero General Public License version 3 or
  5. * later.
  6. * See the COPYING-README file.
  7. */
  8. namespace Test\User;
  9. use OC\AppFramework\Http\Request;
  10. use OC\Authentication\Events\LoginFailed;
  11. use OC\Authentication\Exceptions\InvalidTokenException;
  12. use OC\Authentication\Exceptions\PasswordLoginForbiddenException;
  13. use OC\Authentication\Token\IProvider;
  14. use OC\Authentication\Token\IToken;
  15. use OC\Security\Bruteforce\Throttler;
  16. use OC\Session\Memory;
  17. use OC\User\LoginException;
  18. use OC\User\Manager;
  19. use OC\User\Session;
  20. use OC\User\User;
  21. use OCA\DAV\Connector\Sabre\Auth;
  22. use OCP\AppFramework\Utility\ITimeFactory;
  23. use OCP\EventDispatcher\IEventDispatcher;
  24. use OCP\ICacheFactory;
  25. use OCP\IConfig;
  26. use OCP\IRequest;
  27. use OCP\IRequestId;
  28. use OCP\ISession;
  29. use OCP\IUser;
  30. use OCP\Lockdown\ILockdownManager;
  31. use OCP\Security\ISecureRandom;
  32. use OCP\User\Events\PostLoginEvent;
  33. use PHPUnit\Framework\MockObject\MockObject;
  34. use Psr\Log\LoggerInterface;
  35. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  36. use OC\Security\CSRF\CsrfTokenManager;
  37. /**
  38. * @group DB
  39. * @package Test\User
  40. */
  41. class SessionTest extends \Test\TestCase {
  42. /** @var ITimeFactory|MockObject */
  43. private $timeFactory;
  44. /** @var IProvider|MockObject */
  45. private $tokenProvider;
  46. /** @var IConfig|MockObject */
  47. private $config;
  48. /** @var Throttler|MockObject */
  49. private $throttler;
  50. /** @var ISecureRandom|MockObject */
  51. private $random;
  52. /** @var Manager|MockObject */
  53. private $manager;
  54. /** @var ISession|MockObject */
  55. private $session;
  56. /** @var Session|MockObject */
  57. private $userSession;
  58. /** @var ILockdownManager|MockObject */
  59. private $lockdownManager;
  60. /** @var LoggerInterface|MockObject */
  61. private $logger;
  62. /** @var IEventDispatcher|MockObject */
  63. private $dispatcher;
  64. protected function setUp(): void {
  65. parent::setUp();
  66. $this->timeFactory = $this->createMock(ITimeFactory::class);
  67. $this->timeFactory->expects($this->any())
  68. ->method('getTime')
  69. ->willReturn(10000);
  70. $this->tokenProvider = $this->createMock(IProvider::class);
  71. $this->config = $this->createMock(IConfig::class);
  72. $this->throttler = $this->createMock(Throttler::class);
  73. $this->random = $this->createMock(ISecureRandom::class);
  74. $this->manager = $this->createMock(Manager::class);
  75. $this->session = $this->createMock(ISession::class);
  76. $this->lockdownManager = $this->createMock(ILockdownManager::class);
  77. $this->logger = $this->createMock(LoggerInterface::class);
  78. $this->dispatcher = $this->createMock(IEventDispatcher::class);
  79. $this->userSession = $this->getMockBuilder(Session::class)
  80. ->setConstructorArgs([
  81. $this->manager,
  82. $this->session,
  83. $this->timeFactory,
  84. $this->tokenProvider,
  85. $this->config,
  86. $this->random,
  87. $this->lockdownManager,
  88. $this->logger,
  89. $this->dispatcher
  90. ])
  91. ->setMethods([
  92. 'setMagicInCookie',
  93. ])
  94. ->getMock();
  95. \OC_User::setIncognitoMode(false);
  96. }
  97. public function isLoggedInData() {
  98. return [
  99. [true],
  100. [false],
  101. ];
  102. }
  103. /**
  104. * @dataProvider isLoggedInData
  105. */
  106. public function testIsLoggedIn($isLoggedIn) {
  107. $session = $this->getMockBuilder(Memory::class)->setConstructorArgs([''])->getMock();
  108. $manager = $this->createMock(Manager::class);
  109. $userSession = $this->getMockBuilder(Session::class)
  110. ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
  111. ->setMethods([
  112. 'getUser'
  113. ])
  114. ->getMock();
  115. $user = new User('sepp', null, $this->createMock(EventDispatcherInterface::class));
  116. $userSession->expects($this->once())
  117. ->method('getUser')
  118. ->willReturn($isLoggedIn ? $user : null);
  119. $this->assertEquals($isLoggedIn, $userSession->isLoggedIn());
  120. }
  121. public function testSetUser() {
  122. $session = $this->getMockBuilder(Memory::class)->setConstructorArgs([''])->getMock();
  123. $session->expects($this->once())
  124. ->method('set')
  125. ->with('user_id', 'foo');
  126. $manager = $this->createMock(Manager::class);
  127. $backend = $this->createMock(\Test\Util\User\Dummy::class);
  128. $user = $this->createMock(IUser::class);
  129. $user->expects($this->once())
  130. ->method('getUID')
  131. ->willReturn('foo');
  132. $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher);
  133. $userSession->setUser($user);
  134. }
  135. public function testLoginValidPasswordEnabled() {
  136. $session = $this->getMockBuilder(Memory::class)->setConstructorArgs([''])->getMock();
  137. $session->expects($this->once())
  138. ->method('regenerateId');
  139. $this->tokenProvider->expects($this->once())
  140. ->method('getToken')
  141. ->with('bar')
  142. ->will($this->throwException(new InvalidTokenException()));
  143. $session->expects($this->exactly(2))
  144. ->method('set')
  145. ->with($this->callback(function ($key) {
  146. switch ($key) {
  147. case 'user_id':
  148. case 'loginname':
  149. return true;
  150. break;
  151. default:
  152. return false;
  153. break;
  154. }
  155. }, 'foo'));
  156. $managerMethods = get_class_methods(Manager::class);
  157. //keep following methods intact in order to ensure hooks are working
  158. $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']);
  159. $manager = $this->getMockBuilder(Manager::class)
  160. ->setMethods($mockedManagerMethods)
  161. ->setConstructorArgs([
  162. $this->config,
  163. $this->createMock(EventDispatcherInterface::class),
  164. $this->createMock(ICacheFactory::class),
  165. $this->createMock(IEventDispatcher::class),
  166. ])
  167. ->getMock();
  168. $backend = $this->createMock(\Test\Util\User\Dummy::class);
  169. $user = $this->createMock(IUser::class);
  170. $user->expects($this->any())
  171. ->method('isEnabled')
  172. ->willReturn(true);
  173. $user->expects($this->any())
  174. ->method('getUID')
  175. ->willReturn('foo');
  176. $user->expects($this->once())
  177. ->method('updateLastLoginTimestamp');
  178. $manager->expects($this->once())
  179. ->method('checkPasswordNoLogging')
  180. ->with('foo', 'bar')
  181. ->willReturn($user);
  182. $userSession = $this->getMockBuilder(Session::class)
  183. ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
  184. ->setMethods([
  185. 'prepareUserLogin'
  186. ])
  187. ->getMock();
  188. $userSession->expects($this->once())
  189. ->method('prepareUserLogin');
  190. $this->dispatcher->expects($this->once())
  191. ->method('dispatchTyped')
  192. ->with(
  193. $this->callback(function (PostLoginEvent $e) {
  194. return $e->getUser()->getUID() === 'foo' &&
  195. $e->getPassword() === 'bar' &&
  196. $e->isTokenLogin() === false;
  197. })
  198. );
  199. $userSession->login('foo', 'bar');
  200. $this->assertEquals($user, $userSession->getUser());
  201. }
  202. public function testLoginValidPasswordDisabled() {
  203. $this->expectException(LoginException::class);
  204. $session = $this->getMockBuilder(Memory::class)->setConstructorArgs([''])->getMock();
  205. $session->expects($this->never())
  206. ->method('set');
  207. $session->expects($this->once())
  208. ->method('regenerateId');
  209. $this->tokenProvider->expects($this->once())
  210. ->method('getToken')
  211. ->with('bar')
  212. ->will($this->throwException(new InvalidTokenException()));
  213. $managerMethods = get_class_methods(Manager::class);
  214. //keep following methods intact in order to ensure hooks are working
  215. $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']);
  216. $manager = $this->getMockBuilder(Manager::class)
  217. ->setMethods($mockedManagerMethods)
  218. ->setConstructorArgs([
  219. $this->config,
  220. $this->createMock(EventDispatcherInterface::class),
  221. $this->createMock(ICacheFactory::class),
  222. $this->createMock(IEventDispatcher::class),
  223. ])
  224. ->getMock();
  225. $user = $this->createMock(IUser::class);
  226. $user->expects($this->any())
  227. ->method('isEnabled')
  228. ->willReturn(false);
  229. $user->expects($this->never())
  230. ->method('updateLastLoginTimestamp');
  231. $manager->expects($this->once())
  232. ->method('checkPasswordNoLogging')
  233. ->with('foo', 'bar')
  234. ->willReturn($user);
  235. $this->dispatcher->expects($this->never())
  236. ->method('dispatch');
  237. $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher);
  238. $userSession->login('foo', 'bar');
  239. }
  240. public function testLoginInvalidPassword() {
  241. $session = $this->getMockBuilder(Memory::class)->setConstructorArgs([''])->getMock();
  242. $managerMethods = get_class_methods(Manager::class);
  243. //keep following methods intact in order to ensure hooks are working
  244. $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']);
  245. $manager = $this->getMockBuilder(Manager::class)
  246. ->setMethods($mockedManagerMethods)
  247. ->setConstructorArgs([
  248. $this->config,
  249. $this->createMock(EventDispatcherInterface::class),
  250. $this->createMock(ICacheFactory::class),
  251. $this->createMock(IEventDispatcher::class),
  252. ])
  253. ->getMock();
  254. $backend = $this->createMock(\Test\Util\User\Dummy::class);
  255. $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher);
  256. $user = $this->createMock(IUser::class);
  257. $session->expects($this->never())
  258. ->method('set');
  259. $session->expects($this->once())
  260. ->method('regenerateId');
  261. $this->tokenProvider->expects($this->once())
  262. ->method('getToken')
  263. ->with('bar')
  264. ->will($this->throwException(new InvalidTokenException()));
  265. $user->expects($this->never())
  266. ->method('isEnabled');
  267. $user->expects($this->never())
  268. ->method('updateLastLoginTimestamp');
  269. $manager->expects($this->once())
  270. ->method('checkPasswordNoLogging')
  271. ->with('foo', 'bar')
  272. ->willReturn(false);
  273. $this->dispatcher->expects($this->never())
  274. ->method('dispatch');
  275. $userSession->login('foo', 'bar');
  276. }
  277. public function testLoginNonExisting() {
  278. $session = $this->getMockBuilder(Memory::class)->setConstructorArgs([''])->getMock();
  279. $manager = $this->createMock(Manager::class);
  280. $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher);
  281. $session->expects($this->never())
  282. ->method('set');
  283. $session->expects($this->once())
  284. ->method('regenerateId');
  285. $this->tokenProvider->expects($this->once())
  286. ->method('getToken')
  287. ->with('bar')
  288. ->will($this->throwException(new InvalidTokenException()));
  289. $manager->expects($this->once())
  290. ->method('checkPasswordNoLogging')
  291. ->with('foo', 'bar')
  292. ->willReturn(false);
  293. $userSession->login('foo', 'bar');
  294. }
  295. public function testLogClientInNoTokenPasswordWith2fa() {
  296. $this->expectException(PasswordLoginForbiddenException::class);
  297. $manager = $this->createMock(Manager::class);
  298. $session = $this->createMock(ISession::class);
  299. $request = $this->createMock(IRequest::class);
  300. /** @var Session $userSession */
  301. $userSession = $this->getMockBuilder(Session::class)
  302. ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
  303. ->setMethods(['login', 'supportsCookies', 'createSessionToken', 'getUser'])
  304. ->getMock();
  305. $this->tokenProvider->expects($this->once())
  306. ->method('getToken')
  307. ->with('doe')
  308. ->will($this->throwException(new InvalidTokenException()));
  309. $this->config->expects($this->once())
  310. ->method('getSystemValueBool')
  311. ->with('token_auth_enforced', false)
  312. ->willReturn(true);
  313. $request
  314. ->expects($this->any())
  315. ->method('getRemoteAddress')
  316. ->willReturn('192.168.0.1');
  317. $this->throttler
  318. ->expects($this->once())
  319. ->method('sleepDelayOrThrowOnMax')
  320. ->with('192.168.0.1');
  321. $this->throttler
  322. ->expects($this->any())
  323. ->method('getDelay')
  324. ->with('192.168.0.1')
  325. ->willReturn(0);
  326. $userSession->logClientIn('john', 'doe', $request, $this->throttler);
  327. }
  328. public function testLogClientInUnexist() {
  329. $manager = $this->createMock(Manager::class);
  330. $session = $this->createMock(ISession::class);
  331. $request = $this->createMock(IRequest::class);
  332. /** @var Session $userSession */
  333. $userSession = $this->getMockBuilder(Session::class)
  334. ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
  335. ->setMethods(['login', 'supportsCookies', 'createSessionToken', 'getUser'])
  336. ->getMock();
  337. $this->tokenProvider->expects($this->once())
  338. ->method('getToken')
  339. ->with('doe')
  340. ->will($this->throwException(new InvalidTokenException()));
  341. $this->config->expects($this->once())
  342. ->method('getSystemValueBool')
  343. ->with('token_auth_enforced', false)
  344. ->willReturn(false);
  345. $manager->method('getByEmail')
  346. ->with('unexist')
  347. ->willReturn([]);
  348. $this->assertFalse($userSession->logClientIn('unexist', 'doe', $request, $this->throttler));
  349. }
  350. public function testLogClientInWithTokenPassword() {
  351. $manager = $this->createMock(Manager::class);
  352. $session = $this->createMock(ISession::class);
  353. $request = $this->createMock(IRequest::class);
  354. /** @var Session $userSession */
  355. $userSession = $this->getMockBuilder(Session::class)
  356. ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
  357. ->setMethods(['isTokenPassword', 'login', 'supportsCookies', 'createSessionToken', 'getUser'])
  358. ->getMock();
  359. $userSession->expects($this->once())
  360. ->method('isTokenPassword')
  361. ->willReturn(true);
  362. $userSession->expects($this->once())
  363. ->method('login')
  364. ->with('john', 'I-AM-AN-APP-PASSWORD')
  365. ->willReturn(true);
  366. $session->expects($this->once())
  367. ->method('set')
  368. ->with('app_password', 'I-AM-AN-APP-PASSWORD');
  369. $request
  370. ->expects($this->any())
  371. ->method('getRemoteAddress')
  372. ->willReturn('192.168.0.1');
  373. $this->throttler
  374. ->expects($this->once())
  375. ->method('sleepDelayOrThrowOnMax')
  376. ->with('192.168.0.1');
  377. $this->throttler
  378. ->expects($this->any())
  379. ->method('getDelay')
  380. ->with('192.168.0.1')
  381. ->willReturn(0);
  382. $this->assertTrue($userSession->logClientIn('john', 'I-AM-AN-APP-PASSWORD', $request, $this->throttler));
  383. }
  384. public function testLogClientInNoTokenPasswordNo2fa() {
  385. $this->expectException(PasswordLoginForbiddenException::class);
  386. $manager = $this->createMock(Manager::class);
  387. $session = $this->createMock(ISession::class);
  388. $request = $this->createMock(IRequest::class);
  389. /** @var Session $userSession */
  390. $userSession = $this->getMockBuilder(Session::class)
  391. ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
  392. ->setMethods(['login', 'isTwoFactorEnforced'])
  393. ->getMock();
  394. $this->tokenProvider->expects($this->once())
  395. ->method('getToken')
  396. ->with('doe')
  397. ->will($this->throwException(new InvalidTokenException()));
  398. $this->config->expects($this->once())
  399. ->method('getSystemValueBool')
  400. ->with('token_auth_enforced', false)
  401. ->willReturn(false);
  402. $userSession->expects($this->once())
  403. ->method('isTwoFactorEnforced')
  404. ->with('john')
  405. ->willReturn(true);
  406. $request
  407. ->expects($this->any())
  408. ->method('getRemoteAddress')
  409. ->willReturn('192.168.0.1');
  410. $this->throttler
  411. ->expects($this->once())
  412. ->method('sleepDelayOrThrowOnMax')
  413. ->with('192.168.0.1');
  414. $this->throttler
  415. ->expects($this->any())
  416. ->method('getDelay')
  417. ->with('192.168.0.1')
  418. ->willReturn(0);
  419. $userSession->logClientIn('john', 'doe', $request, $this->throttler);
  420. }
  421. public function testRememberLoginValidToken() {
  422. $session = $this->getMockBuilder(Memory::class)->setConstructorArgs([''])->getMock();
  423. $managerMethods = get_class_methods(Manager::class);
  424. //keep following methods intact in order to ensure hooks are working
  425. $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']);
  426. $manager = $this->getMockBuilder(Manager::class)
  427. ->setMethods($mockedManagerMethods)
  428. ->setConstructorArgs([
  429. $this->config,
  430. $this->createMock(EventDispatcherInterface::class),
  431. $this->createMock(ICacheFactory::class),
  432. $this->createMock(IEventDispatcher::class),
  433. ])
  434. ->getMock();
  435. $userSession = $this->getMockBuilder(Session::class)
  436. //override, otherwise tests will fail because of setcookie()
  437. ->setMethods(['setMagicInCookie', 'setLoginName'])
  438. ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
  439. ->getMock();
  440. $user = $this->createMock(IUser::class);
  441. $token = 'goodToken';
  442. $oldSessionId = 'sess321';
  443. $sessionId = 'sess123';
  444. $session->expects($this->once())
  445. ->method('regenerateId');
  446. $manager->expects($this->once())
  447. ->method('get')
  448. ->with('foo')
  449. ->willReturn($user);
  450. $this->config->expects($this->once())
  451. ->method('getUserKeys')
  452. ->with('foo', 'login_token')
  453. ->willReturn([$token]);
  454. $this->config->expects($this->once())
  455. ->method('deleteUserValue')
  456. ->with('foo', 'login_token', $token);
  457. $this->random->expects($this->once())
  458. ->method('generate')
  459. ->with(32)
  460. ->willReturn('abcdefg123456');
  461. $this->config->expects($this->once())
  462. ->method('setUserValue')
  463. ->with('foo', 'login_token', 'abcdefg123456', 10000);
  464. $tokenObject = $this->createMock(IToken::class);
  465. $tokenObject->expects($this->once())
  466. ->method('getLoginName')
  467. ->willReturn('foobar');
  468. $tokenObject->method('getId')
  469. ->willReturn(42);
  470. $session->expects($this->once())
  471. ->method('getId')
  472. ->willReturn($sessionId);
  473. $this->tokenProvider->expects($this->once())
  474. ->method('renewSessionToken')
  475. ->with($oldSessionId, $sessionId)
  476. ->willReturn($tokenObject);
  477. $this->tokenProvider->expects($this->never())
  478. ->method('getToken');
  479. $user->expects($this->any())
  480. ->method('getUID')
  481. ->willReturn('foo');
  482. $userSession->expects($this->once())
  483. ->method('setMagicInCookie');
  484. $user->expects($this->once())
  485. ->method('updateLastLoginTimestamp');
  486. $setUID = false;
  487. $session
  488. ->method('set')
  489. ->willReturnCallback(function ($k, $v) use (&$setUID) {
  490. if ($k === 'user_id' && $v === 'foo') {
  491. $setUID = true;
  492. }
  493. });
  494. $userSession->expects($this->once())
  495. ->method('setLoginName')
  496. ->willReturn('foobar');
  497. $granted = $userSession->loginWithCookie('foo', $token, $oldSessionId);
  498. $this->assertTrue($setUID);
  499. $this->assertTrue($granted);
  500. }
  501. public function testRememberLoginInvalidSessionToken() {
  502. $session = $this->getMockBuilder(Memory::class)->setConstructorArgs([''])->getMock();
  503. $managerMethods = get_class_methods(Manager::class);
  504. //keep following methods intact in order to ensure hooks are working
  505. $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']);
  506. $manager = $this->getMockBuilder(Manager::class)
  507. ->setMethods($mockedManagerMethods)
  508. ->setConstructorArgs([
  509. $this->config,
  510. $this->createMock(EventDispatcherInterface::class),
  511. $this->createMock(ICacheFactory::class),
  512. $this->createMock(IEventDispatcher::class),
  513. ])
  514. ->getMock();
  515. $userSession = $this->getMockBuilder(Session::class)
  516. //override, otherwise tests will fail because of setcookie()
  517. ->setMethods(['setMagicInCookie'])
  518. ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
  519. ->getMock();
  520. $user = $this->createMock(IUser::class);
  521. $token = 'goodToken';
  522. $oldSessionId = 'sess321';
  523. $sessionId = 'sess123';
  524. $session->expects($this->once())
  525. ->method('regenerateId');
  526. $manager->expects($this->once())
  527. ->method('get')
  528. ->with('foo')
  529. ->willReturn($user);
  530. $this->config->expects($this->once())
  531. ->method('getUserKeys')
  532. ->with('foo', 'login_token')
  533. ->willReturn([$token]);
  534. $this->config->expects($this->once())
  535. ->method('deleteUserValue')
  536. ->with('foo', 'login_token', $token);
  537. $this->config->expects($this->once())
  538. ->method('setUserValue'); // TODO: mock new random value
  539. $session->expects($this->once())
  540. ->method('getId')
  541. ->willReturn($sessionId);
  542. $this->tokenProvider->expects($this->once())
  543. ->method('renewSessionToken')
  544. ->with($oldSessionId, $sessionId)
  545. ->will($this->throwException(new InvalidTokenException()));
  546. $user->expects($this->never())
  547. ->method('getUID')
  548. ->willReturn('foo');
  549. $userSession->expects($this->never())
  550. ->method('setMagicInCookie');
  551. $user->expects($this->never())
  552. ->method('updateLastLoginTimestamp');
  553. $session->expects($this->never())
  554. ->method('set')
  555. ->with('user_id', 'foo');
  556. $granted = $userSession->loginWithCookie('foo', $token, $oldSessionId);
  557. $this->assertFalse($granted);
  558. }
  559. public function testRememberLoginInvalidToken() {
  560. $session = $this->getMockBuilder(Memory::class)->setConstructorArgs([''])->getMock();
  561. $managerMethods = get_class_methods(Manager::class);
  562. //keep following methods intact in order to ensure hooks are working
  563. $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']);
  564. $manager = $this->getMockBuilder(Manager::class)
  565. ->setMethods($mockedManagerMethods)
  566. ->setConstructorArgs([
  567. $this->config,
  568. $this->createMock(EventDispatcherInterface::class),
  569. $this->createMock(ICacheFactory::class),
  570. $this->createMock(IEventDispatcher::class),
  571. ])
  572. ->getMock();
  573. $userSession = $this->getMockBuilder(Session::class)
  574. //override, otherwise tests will fail because of setcookie()
  575. ->setMethods(['setMagicInCookie'])
  576. ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
  577. ->getMock();
  578. $user = $this->createMock(IUser::class);
  579. $token = 'goodToken';
  580. $oldSessionId = 'sess321';
  581. $session->expects($this->once())
  582. ->method('regenerateId');
  583. $manager->expects($this->once())
  584. ->method('get')
  585. ->with('foo')
  586. ->willReturn($user);
  587. $this->config->expects($this->once())
  588. ->method('getUserKeys')
  589. ->with('foo', 'login_token')
  590. ->willReturn(['anothertoken']);
  591. $this->config->expects($this->never())
  592. ->method('deleteUserValue')
  593. ->with('foo', 'login_token', $token);
  594. $this->tokenProvider->expects($this->never())
  595. ->method('renewSessionToken');
  596. $userSession->expects($this->never())
  597. ->method('setMagicInCookie');
  598. $user->expects($this->never())
  599. ->method('updateLastLoginTimestamp');
  600. $session->expects($this->never())
  601. ->method('set')
  602. ->with('user_id', 'foo');
  603. $granted = $userSession->loginWithCookie('foo', $token, $oldSessionId);
  604. $this->assertFalse($granted);
  605. }
  606. public function testRememberLoginInvalidUser() {
  607. $session = $this->getMockBuilder(Memory::class)->setConstructorArgs([''])->getMock();
  608. $managerMethods = get_class_methods(Manager::class);
  609. //keep following methods intact in order to ensure hooks are working
  610. $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']);
  611. $manager = $this->getMockBuilder(Manager::class)
  612. ->setMethods($mockedManagerMethods)
  613. ->setConstructorArgs([
  614. $this->config,
  615. $this->createMock(EventDispatcherInterface::class),
  616. $this->createMock(ICacheFactory::class),
  617. $this->createMock(IEventDispatcher::class),
  618. ])
  619. ->getMock();
  620. $userSession = $this->getMockBuilder(Session::class)
  621. //override, otherwise tests will fail because of setcookie()
  622. ->setMethods(['setMagicInCookie'])
  623. ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
  624. ->getMock();
  625. $token = 'goodToken';
  626. $oldSessionId = 'sess321';
  627. $session->expects($this->once())
  628. ->method('regenerateId');
  629. $manager->expects($this->once())
  630. ->method('get')
  631. ->with('foo')
  632. ->willReturn(null);
  633. $this->config->expects($this->never())
  634. ->method('getUserKeys')
  635. ->with('foo', 'login_token')
  636. ->willReturn(['anothertoken']);
  637. $this->tokenProvider->expects($this->never())
  638. ->method('renewSessionToken');
  639. $userSession->expects($this->never())
  640. ->method('setMagicInCookie');
  641. $session->expects($this->never())
  642. ->method('set')
  643. ->with('user_id', 'foo');
  644. $granted = $userSession->loginWithCookie('foo', $token, $oldSessionId);
  645. $this->assertFalse($granted);
  646. }
  647. public function testActiveUserAfterSetSession() {
  648. $users = [
  649. 'foo' => new User('foo', null, $this->createMock(EventDispatcherInterface::class)),
  650. 'bar' => new User('bar', null, $this->createMock(EventDispatcherInterface::class))
  651. ];
  652. $manager = $this->getMockBuilder(Manager::class)
  653. ->disableOriginalConstructor()
  654. ->getMock();
  655. $manager->expects($this->any())
  656. ->method('get')
  657. ->willReturnCallback(function ($uid) use ($users) {
  658. return $users[$uid];
  659. });
  660. $session = new Memory('');
  661. $session->set('user_id', 'foo');
  662. $userSession = $this->getMockBuilder(Session::class)
  663. ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
  664. ->setMethods([
  665. 'validateSession'
  666. ])
  667. ->getMock();
  668. $userSession->expects($this->any())
  669. ->method('validateSession');
  670. $this->assertEquals($users['foo'], $userSession->getUser());
  671. $session2 = new Memory('');
  672. $session2->set('user_id', 'bar');
  673. $userSession->setSession($session2);
  674. $this->assertEquals($users['bar'], $userSession->getUser());
  675. }
  676. public function testCreateSessionToken() {
  677. $manager = $this->createMock(Manager::class);
  678. $session = $this->createMock(ISession::class);
  679. $user = $this->createMock(IUser::class);
  680. $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher);
  681. $requestId = $this->createMock(IRequestId::class);
  682. $config = $this->createMock(IConfig::class);
  683. $csrf = $this->getMockBuilder(CsrfTokenManager::class)
  684. ->disableOriginalConstructor()
  685. ->getMock();
  686. $request = new Request([
  687. 'server' => [
  688. 'HTTP_USER_AGENT' => 'Firefox',
  689. ]
  690. ], $requestId, $config, $csrf);
  691. $uid = 'user123';
  692. $loginName = 'User123';
  693. $password = 'passme';
  694. $sessionId = 'abcxyz';
  695. $manager->expects($this->once())
  696. ->method('get')
  697. ->with($uid)
  698. ->willReturn($user);
  699. $session->expects($this->once())
  700. ->method('getId')
  701. ->willReturn($sessionId);
  702. $this->tokenProvider->expects($this->once())
  703. ->method('getToken')
  704. ->with($password)
  705. ->will($this->throwException(new InvalidTokenException()));
  706. $this->tokenProvider->expects($this->once())
  707. ->method('generateToken')
  708. ->with($sessionId, $uid, $loginName, $password, 'Firefox', IToken::TEMPORARY_TOKEN, IToken::DO_NOT_REMEMBER);
  709. $this->assertTrue($userSession->createSessionToken($request, $uid, $loginName, $password));
  710. }
  711. public function testCreateRememberedSessionToken() {
  712. $manager = $this->createMock(Manager::class);
  713. $session = $this->createMock(ISession::class);
  714. $user = $this->createMock(IUser::class);
  715. $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher);
  716. $requestId = $this->createMock(IRequestId::class);
  717. $config = $this->createMock(IConfig::class);
  718. $csrf = $this->getMockBuilder(CsrfTokenManager::class)
  719. ->disableOriginalConstructor()
  720. ->getMock();
  721. $request = new Request([
  722. 'server' => [
  723. 'HTTP_USER_AGENT' => 'Firefox',
  724. ]
  725. ], $requestId, $config, $csrf);
  726. $uid = 'user123';
  727. $loginName = 'User123';
  728. $password = 'passme';
  729. $sessionId = 'abcxyz';
  730. $manager->expects($this->once())
  731. ->method('get')
  732. ->with($uid)
  733. ->willReturn($user);
  734. $session->expects($this->once())
  735. ->method('getId')
  736. ->willReturn($sessionId);
  737. $this->tokenProvider->expects($this->once())
  738. ->method('getToken')
  739. ->with($password)
  740. ->will($this->throwException(new InvalidTokenException()));
  741. $this->tokenProvider->expects($this->once())
  742. ->method('generateToken')
  743. ->with($sessionId, $uid, $loginName, $password, 'Firefox', IToken::TEMPORARY_TOKEN, IToken::REMEMBER);
  744. $this->assertTrue($userSession->createSessionToken($request, $uid, $loginName, $password, true));
  745. }
  746. public function testCreateSessionTokenWithTokenPassword() {
  747. $manager = $this->getMockBuilder(Manager::class)
  748. ->disableOriginalConstructor()
  749. ->getMock();
  750. $session = $this->createMock(ISession::class);
  751. $token = $this->createMock(IToken::class);
  752. $user = $this->createMock(IUser::class);
  753. $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher);
  754. $requestId = $this->createMock(IRequestId::class);
  755. $config = $this->createMock(IConfig::class);
  756. $csrf = $this->getMockBuilder(CsrfTokenManager::class)
  757. ->disableOriginalConstructor()
  758. ->getMock();
  759. $request = new Request([
  760. 'server' => [
  761. 'HTTP_USER_AGENT' => 'Firefox',
  762. ]
  763. ], $requestId, $config, $csrf);
  764. $uid = 'user123';
  765. $loginName = 'User123';
  766. $password = 'iamatoken';
  767. $realPassword = 'passme';
  768. $sessionId = 'abcxyz';
  769. $manager->expects($this->once())
  770. ->method('get')
  771. ->with($uid)
  772. ->willReturn($user);
  773. $session->expects($this->once())
  774. ->method('getId')
  775. ->willReturn($sessionId);
  776. $this->tokenProvider->expects($this->once())
  777. ->method('getToken')
  778. ->with($password)
  779. ->willReturn($token);
  780. $this->tokenProvider->expects($this->once())
  781. ->method('getPassword')
  782. ->with($token, $password)
  783. ->willReturn($realPassword);
  784. $this->tokenProvider->expects($this->once())
  785. ->method('generateToken')
  786. ->with($sessionId, $uid, $loginName, $realPassword, 'Firefox', IToken::TEMPORARY_TOKEN, IToken::DO_NOT_REMEMBER);
  787. $this->assertTrue($userSession->createSessionToken($request, $uid, $loginName, $password));
  788. }
  789. public function testCreateSessionTokenWithNonExistentUser() {
  790. $manager = $this->getMockBuilder(Manager::class)
  791. ->disableOriginalConstructor()
  792. ->getMock();
  793. $session = $this->createMock(ISession::class);
  794. $userSession = new Session($manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher);
  795. $request = $this->createMock(IRequest::class);
  796. $uid = 'user123';
  797. $loginName = 'User123';
  798. $password = 'passme';
  799. $manager->expects($this->once())
  800. ->method('get')
  801. ->with($uid)
  802. ->willReturn(null);
  803. $this->assertFalse($userSession->createSessionToken($request, $uid, $loginName, $password));
  804. }
  805. public function testCreateRememberMeToken() {
  806. $user = $this->createMock(IUser::class);
  807. $user
  808. ->expects($this->exactly(2))
  809. ->method('getUID')
  810. ->willReturn('UserUid');
  811. $this->random
  812. ->expects($this->once())
  813. ->method('generate')
  814. ->with(32)
  815. ->willReturn('LongRandomToken');
  816. $this->config
  817. ->expects($this->once())
  818. ->method('setUserValue')
  819. ->with('UserUid', 'login_token', 'LongRandomToken', 10000);
  820. $this->userSession
  821. ->expects($this->once())
  822. ->method('setMagicInCookie')
  823. ->with('UserUid', 'LongRandomToken');
  824. $this->userSession->createRememberMeToken($user);
  825. }
  826. public function testTryBasicAuthLoginValid() {
  827. $request = $this->createMock(Request::class);
  828. $request->method('__get')
  829. ->willReturn([
  830. 'PHP_AUTH_USER' => 'username',
  831. 'PHP_AUTH_PW' => 'password',
  832. ]);
  833. $request->method('__isset')
  834. ->with('server')
  835. ->willReturn(true);
  836. $davAuthenticatedSet = false;
  837. $lastPasswordConfirmSet = false;
  838. $this->session
  839. ->method('set')
  840. ->willReturnCallback(function ($k, $v) use (&$davAuthenticatedSet, &$lastPasswordConfirmSet) {
  841. switch ($k) {
  842. case Auth::DAV_AUTHENTICATED:
  843. $davAuthenticatedSet = $v;
  844. return;
  845. case 'last-password-confirm':
  846. $lastPasswordConfirmSet = 1000;
  847. return;
  848. default:
  849. throw new \Exception();
  850. }
  851. });
  852. $userSession = $this->getMockBuilder(Session::class)
  853. ->setConstructorArgs([
  854. $this->manager,
  855. $this->session,
  856. $this->timeFactory,
  857. $this->tokenProvider,
  858. $this->config,
  859. $this->random,
  860. $this->lockdownManager,
  861. $this->logger,
  862. $this->dispatcher
  863. ])
  864. ->setMethods([
  865. 'logClientIn',
  866. 'getUser',
  867. ])
  868. ->getMock();
  869. /** @var Session|MockObject */
  870. $userSession->expects($this->once())
  871. ->method('logClientIn')
  872. ->with(
  873. $this->equalTo('username'),
  874. $this->equalTo('password'),
  875. $this->equalTo($request),
  876. $this->equalTo($this->throttler)
  877. )->willReturn(true);
  878. $user = $this->createMock(IUser::class);
  879. $user->method('getUID')->willReturn('username');
  880. $userSession->expects($this->once())
  881. ->method('getUser')
  882. ->willReturn($user);
  883. $this->assertTrue($userSession->tryBasicAuthLogin($request, $this->throttler));
  884. $this->assertSame('username', $davAuthenticatedSet);
  885. $this->assertSame(1000, $lastPasswordConfirmSet);
  886. }
  887. public function testTryBasicAuthLoginNoLogin() {
  888. $request = $this->createMock(Request::class);
  889. $request->method('__get')
  890. ->willReturn([]);
  891. $request->method('__isset')
  892. ->with('server')
  893. ->willReturn(true);
  894. $this->session->expects($this->never())
  895. ->method($this->anything());
  896. $userSession = $this->getMockBuilder(Session::class)
  897. ->setConstructorArgs([
  898. $this->manager,
  899. $this->session,
  900. $this->timeFactory,
  901. $this->tokenProvider,
  902. $this->config,
  903. $this->random,
  904. $this->lockdownManager,
  905. $this->logger,
  906. $this->dispatcher
  907. ])
  908. ->setMethods([
  909. 'logClientIn',
  910. ])
  911. ->getMock();
  912. /** @var Session|MockObject */
  913. $userSession->expects($this->never())
  914. ->method('logClientIn');
  915. $this->assertFalse($userSession->tryBasicAuthLogin($request, $this->throttler));
  916. }
  917. public function testUpdateTokens() {
  918. $this->tokenProvider->expects($this->once())
  919. ->method('updatePasswords')
  920. ->with('uid', 'pass');
  921. $this->userSession->updateTokens('uid', 'pass');
  922. }
  923. public function testLogClientInThrottlerUsername() {
  924. $manager = $this->createMock(Manager::class);
  925. $session = $this->createMock(ISession::class);
  926. $request = $this->createMock(IRequest::class);
  927. /** @var Session $userSession */
  928. $userSession = $this->getMockBuilder(Session::class)
  929. ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
  930. ->setMethods(['isTokenPassword', 'login', 'supportsCookies', 'createSessionToken', 'getUser'])
  931. ->getMock();
  932. $userSession->expects($this->once())
  933. ->method('isTokenPassword')
  934. ->willReturn(true);
  935. $userSession->expects($this->once())
  936. ->method('login')
  937. ->with('john', 'I-AM-AN-PASSWORD')
  938. ->willReturn(false);
  939. $session->expects($this->never())
  940. ->method('set');
  941. $request
  942. ->method('getRemoteAddress')
  943. ->willReturn('192.168.0.1');
  944. $this->throttler
  945. ->expects($this->exactly(2))
  946. ->method('sleepDelayOrThrowOnMax')
  947. ->with('192.168.0.1');
  948. $this->throttler
  949. ->expects($this->any())
  950. ->method('getDelay')
  951. ->with('192.168.0.1')
  952. ->willReturn(0);
  953. $this->throttler
  954. ->expects($this->once())
  955. ->method('registerAttempt')
  956. ->with('login', '192.168.0.1', ['user' => 'john']);
  957. $this->dispatcher
  958. ->expects($this->once())
  959. ->method('dispatchTyped')
  960. ->with(new LoginFailed('john', 'I-AM-AN-PASSWORD'));
  961. $this->assertFalse($userSession->logClientIn('john', 'I-AM-AN-PASSWORD', $request, $this->throttler));
  962. }
  963. public function testLogClientInThrottlerEmail() {
  964. $manager = $this->createMock(Manager::class);
  965. $session = $this->createMock(ISession::class);
  966. $request = $this->createMock(IRequest::class);
  967. /** @var Session $userSession */
  968. $userSession = $this->getMockBuilder(Session::class)
  969. ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher])
  970. ->setMethods(['isTokenPassword', 'login', 'supportsCookies', 'createSessionToken', 'getUser'])
  971. ->getMock();
  972. $userSession->expects($this->once())
  973. ->method('isTokenPassword')
  974. ->willReturn(true);
  975. $userSession->expects($this->once())
  976. ->method('login')
  977. ->with('john@foo.bar', 'I-AM-AN-PASSWORD')
  978. ->willReturn(false);
  979. $manager
  980. ->method('getByEmail')
  981. ->with('john@foo.bar')
  982. ->willReturn([]);
  983. $session->expects($this->never())
  984. ->method('set');
  985. $request
  986. ->method('getRemoteAddress')
  987. ->willReturn('192.168.0.1');
  988. $this->throttler
  989. ->expects($this->exactly(2))
  990. ->method('sleepDelayOrThrowOnMax')
  991. ->with('192.168.0.1');
  992. $this->throttler
  993. ->expects($this->any())
  994. ->method('getDelay')
  995. ->with('192.168.0.1')
  996. ->willReturn(0);
  997. $this->throttler
  998. ->expects($this->once())
  999. ->method('registerAttempt')
  1000. ->with('login', '192.168.0.1', ['user' => 'john@foo.bar']);
  1001. $this->dispatcher
  1002. ->expects($this->once())
  1003. ->method('dispatchTyped')
  1004. ->with(new LoginFailed('john@foo.bar', 'I-AM-AN-PASSWORD'));
  1005. $this->assertFalse($userSession->logClientIn('john@foo.bar', 'I-AM-AN-PASSWORD', $request, $this->throttler));
  1006. }
  1007. }