LoginFlowV2ServiceUnitTest.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-only
  5. */
  6. namespace Tests\Core\Data;
  7. use Exception;
  8. use OC\Authentication\Exceptions\InvalidTokenException;
  9. use OC\Authentication\Token\IProvider;
  10. use OC\Authentication\Token\IToken;
  11. use OC\Core\Data\LoginFlowV2Credentials;
  12. use OC\Core\Data\LoginFlowV2Tokens;
  13. use OC\Core\Db\LoginFlowV2;
  14. use OC\Core\Db\LoginFlowV2Mapper;
  15. use OC\Core\Exception\LoginFlowV2NotFoundException;
  16. use OC\Core\Service\LoginFlowV2Service;
  17. use OCP\AppFramework\Db\DoesNotExistException;
  18. use OCP\AppFramework\Utility\ITimeFactory;
  19. use OCP\IConfig;
  20. use OCP\Security\ICrypto;
  21. use OCP\Security\ISecureRandom;
  22. use PHPUnit\Framework\MockObject\MockObject;
  23. use Psr\Log\LoggerInterface;
  24. use Test\TestCase;
  25. /**
  26. * Unit tests for \OC\Core\Service\LoginFlowV2Service
  27. */
  28. class LoginFlowV2ServiceUnitTest extends TestCase {
  29. /** @var \OCP\IConfig */
  30. private $config;
  31. /** @var \OCP\Security\ICrypto */
  32. private $crypto;
  33. /** @var LoggerInterface|MockObject */
  34. private $logger;
  35. /** @var \OC\Core\Db\LoginFlowV2Mapper */
  36. private $mapper;
  37. /** @var \OCP\Security\ISecureRandom */
  38. private $secureRandom;
  39. /** @var \OC\Core\Service\LoginFlowV2Service */
  40. private $subjectUnderTest;
  41. /** @var \OCP\AppFramework\Utility\ITimeFactory */
  42. private $timeFactory;
  43. /** @var \OC\Authentication\Token\IProvider */
  44. private $tokenProvider;
  45. public function setUp(): void {
  46. parent::setUp();
  47. $this->setupSubjectUnderTest();
  48. }
  49. /**
  50. * Setup subject under test with mocked constructor arguments.
  51. *
  52. * Code was moved to separate function to keep setUp function small and clear.
  53. */
  54. private function setupSubjectUnderTest(): void {
  55. $this->config = $this->getMockBuilder(IConfig::class)
  56. ->disableOriginalConstructor()->getMock();
  57. $this->crypto = $this->getMockBuilder(ICrypto::class)
  58. ->disableOriginalConstructor()->getMock();
  59. $this->mapper = $this->getMockBuilder(LoginFlowV2Mapper::class)
  60. ->disableOriginalConstructor()->getMock();
  61. $this->logger = $this->getMockBuilder(LoggerInterface::class)
  62. ->disableOriginalConstructor()->getMock();
  63. $this->tokenProvider = $this->getMockBuilder(IProvider::class)
  64. ->disableOriginalConstructor()->getMock();
  65. $this->secureRandom = $this->getMockBuilder(ISecureRandom::class)
  66. ->disableOriginalConstructor()->getMock();
  67. $this->timeFactory = $this->getMockBuilder(ITimeFactory::class)
  68. ->disableOriginalConstructor()->getMock();
  69. $this->subjectUnderTest = new LoginFlowV2Service(
  70. $this->mapper,
  71. $this->secureRandom,
  72. $this->timeFactory,
  73. $this->config,
  74. $this->crypto,
  75. $this->logger,
  76. $this->tokenProvider
  77. );
  78. }
  79. /**
  80. * Generates for a given password required OpenSSL parts.
  81. *
  82. * @return array Array contains encrypted password, private key and public key.
  83. */
  84. private function getOpenSSLEncryptedPublicAndPrivateKey(string $appPassword): array {
  85. // Create the private and public key
  86. $res = openssl_pkey_new([
  87. 'digest_alg' => 'md5', // take fast algorithm for testing purposes
  88. 'private_key_bits' => 512,
  89. 'private_key_type' => OPENSSL_KEYTYPE_RSA,
  90. ]);
  91. // Extract the private key from $res
  92. openssl_pkey_export($res, $privateKey);
  93. // Extract the public key from $res
  94. $publicKey = openssl_pkey_get_details($res);
  95. $publicKey = $publicKey['key'];
  96. // Encrypt the data to $encrypted using the public key
  97. openssl_public_encrypt($appPassword, $encrypted, $publicKey, OPENSSL_PKCS1_OAEP_PADDING);
  98. return [$encrypted, $privateKey, $publicKey];
  99. }
  100. /*
  101. * Tests for poll
  102. */
  103. public function testPollApptokenCouldNotBeDecrypted() {
  104. $this->expectException(LoginFlowV2NotFoundException::class);
  105. $this->expectExceptionMessage('Apptoken could not be decrypted');
  106. /*
  107. * Cannot be mocked, because functions like getLoginName are magic functions.
  108. * To be able to set internal properties, we have to use the real class here.
  109. */
  110. $loginFlowV2 = new LoginFlowV2();
  111. $loginFlowV2->setLoginName('test');
  112. $loginFlowV2->setServer('test');
  113. $loginFlowV2->setAppPassword('test');
  114. $loginFlowV2->setPrivateKey('test');
  115. $this->mapper->expects($this->once())
  116. ->method('getByPollToken')
  117. ->willReturn($loginFlowV2);
  118. $this->subjectUnderTest->poll('');
  119. }
  120. public function testPollInvalidToken() {
  121. $this->expectException(LoginFlowV2NotFoundException::class);
  122. $this->expectExceptionMessage('Invalid token');
  123. $this->mapper->expects($this->once())
  124. ->method('getByPollToken')
  125. ->willThrowException(new DoesNotExistException(''));
  126. $this->subjectUnderTest->poll('');
  127. }
  128. public function testPollTokenNotYetReady() {
  129. $this->expectException(LoginFlowV2NotFoundException::class);
  130. $this->expectExceptionMessage('Token not yet ready');
  131. $this->subjectUnderTest->poll('');
  132. }
  133. public function testPollRemoveDataFromDb() {
  134. [$encrypted, $privateKey] = $this->getOpenSSLEncryptedPublicAndPrivateKey('test_pass');
  135. $this->crypto->expects($this->once())
  136. ->method('decrypt')
  137. ->willReturn($privateKey);
  138. /*
  139. * Cannot be mocked, because functions like getLoginName are magic functions.
  140. * To be able to set internal properties, we have to use the real class here.
  141. */
  142. $loginFlowV2 = new LoginFlowV2();
  143. $loginFlowV2->setLoginName('test_login');
  144. $loginFlowV2->setServer('test_server');
  145. $loginFlowV2->setAppPassword(base64_encode($encrypted));
  146. $loginFlowV2->setPrivateKey($privateKey);
  147. $this->mapper->expects($this->once())
  148. ->method('delete')
  149. ->with($this->equalTo($loginFlowV2));
  150. $this->mapper->expects($this->once())
  151. ->method('getByPollToken')
  152. ->willReturn($loginFlowV2);
  153. $credentials = $this->subjectUnderTest->poll('');
  154. $this->assertTrue($credentials instanceof LoginFlowV2Credentials);
  155. $this->assertEquals(
  156. [
  157. 'server' => 'test_server',
  158. 'loginName' => 'test_login',
  159. 'appPassword' => 'test_pass',
  160. ],
  161. $credentials->jsonSerialize()
  162. );
  163. }
  164. /*
  165. * Tests for getByLoginToken
  166. */
  167. public function testGetByLoginToken() {
  168. $loginFlowV2 = new LoginFlowV2();
  169. $loginFlowV2->setLoginName('test_login');
  170. $loginFlowV2->setServer('test_server');
  171. $loginFlowV2->setAppPassword('test');
  172. $this->mapper->expects($this->once())
  173. ->method('getByLoginToken')
  174. ->willReturn($loginFlowV2);
  175. $result = $this->subjectUnderTest->getByLoginToken('test_token');
  176. $this->assertTrue($result instanceof LoginFlowV2);
  177. $this->assertEquals('test_server', $result->getServer());
  178. $this->assertEquals('test_login', $result->getLoginName());
  179. $this->assertEquals('test', $result->getAppPassword());
  180. }
  181. public function testGetByLoginTokenLoginTokenInvalid() {
  182. $this->expectException(LoginFlowV2NotFoundException::class);
  183. $this->expectExceptionMessage('Login token invalid');
  184. $this->mapper->expects($this->once())
  185. ->method('getByLoginToken')
  186. ->willThrowException(new DoesNotExistException(''));
  187. $this->subjectUnderTest->getByLoginToken('test_token');
  188. }
  189. /*
  190. * Tests for startLoginFlow
  191. */
  192. public function testStartLoginFlow() {
  193. $loginFlowV2 = new LoginFlowV2();
  194. $this->mapper->expects($this->once())
  195. ->method('getByLoginToken')
  196. ->willReturn($loginFlowV2);
  197. $this->mapper->expects($this->once())
  198. ->method('update');
  199. $this->assertTrue($this->subjectUnderTest->startLoginFlow('test_token'));
  200. }
  201. public function testStartLoginFlowDoesNotExistException() {
  202. $this->mapper->expects($this->once())
  203. ->method('getByLoginToken')
  204. ->willThrowException(new DoesNotExistException(''));
  205. $this->assertFalse($this->subjectUnderTest->startLoginFlow('test_token'));
  206. }
  207. /**
  208. * If an exception not of type DoesNotExistException is thrown,
  209. * it is expected that it is not being handled by startLoginFlow.
  210. */
  211. public function testStartLoginFlowException() {
  212. $this->expectException(Exception::class);
  213. $this->mapper->expects($this->once())
  214. ->method('getByLoginToken')
  215. ->willThrowException(new Exception(''));
  216. $this->subjectUnderTest->startLoginFlow('test_token');
  217. }
  218. /*
  219. * Tests for flowDone
  220. */
  221. public function testFlowDone() {
  222. [,, $publicKey] = $this->getOpenSSLEncryptedPublicAndPrivateKey('test_pass');
  223. $loginFlowV2 = new LoginFlowV2();
  224. $loginFlowV2->setPublicKey($publicKey);
  225. $loginFlowV2->setClientName('client_name');
  226. $this->mapper->expects($this->once())
  227. ->method('getByLoginToken')
  228. ->willReturn($loginFlowV2);
  229. $this->mapper->expects($this->once())
  230. ->method('update');
  231. $this->secureRandom->expects($this->once())
  232. ->method('generate')
  233. ->with(72, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS)
  234. ->willReturn('test_pass');
  235. // session token
  236. $sessionToken = $this->getMockBuilder(IToken::class)->disableOriginalConstructor()->getMock();
  237. $sessionToken->expects($this->once())
  238. ->method('getLoginName')
  239. ->willReturn('login_name');
  240. $this->tokenProvider->expects($this->once())
  241. ->method('getPassword')
  242. ->willReturn('test_pass');
  243. $this->tokenProvider->expects($this->once())
  244. ->method('getToken')
  245. ->willReturn($sessionToken);
  246. $this->tokenProvider->expects($this->once())
  247. ->method('generateToken')
  248. ->with(
  249. 'test_pass',
  250. 'user_id',
  251. 'login_name',
  252. 'test_pass',
  253. 'client_name',
  254. IToken::PERMANENT_TOKEN,
  255. IToken::DO_NOT_REMEMBER
  256. );
  257. $result = $this->subjectUnderTest->flowDone(
  258. 'login_token',
  259. 'session_id',
  260. 'server',
  261. 'user_id'
  262. );
  263. $this->assertTrue($result);
  264. // app password is encrypted and must look like:
  265. // ZACZOOzxTpKz4+KXL5kZ/gCK0xvkaVi/8yzupAn6Ui6+5qCSKvfPKGgeDRKs0sivvSLzk/XSp811SZCZmH0Y3g==
  266. $this->assertMatchesRegularExpression('/[a-zA-Z\/0-9+=]+/', $loginFlowV2->getAppPassword());
  267. $this->assertEquals('server', $loginFlowV2->getServer());
  268. }
  269. public function testFlowDoneDoesNotExistException() {
  270. $this->mapper->expects($this->once())
  271. ->method('getByLoginToken')
  272. ->willThrowException(new DoesNotExistException(''));
  273. $result = $this->subjectUnderTest->flowDone(
  274. 'login_token',
  275. 'session_id',
  276. 'server',
  277. 'user_id'
  278. );
  279. $this->assertFalse($result);
  280. }
  281. public function testFlowDonePasswordlessTokenException() {
  282. $this->tokenProvider->expects($this->once())
  283. ->method('getToken')
  284. ->willThrowException(new InvalidTokenException(''));
  285. $result = $this->subjectUnderTest->flowDone(
  286. 'login_token',
  287. 'session_id',
  288. 'server',
  289. 'user_id'
  290. );
  291. $this->assertFalse($result);
  292. }
  293. /*
  294. * Tests for createTokens
  295. */
  296. public function testCreateTokens() {
  297. $this->config->expects($this->exactly(2))
  298. ->method('getSystemValue')
  299. ->willReturn($this->returnCallback(function ($key) {
  300. // Note: \OCP\IConfig::getSystemValue returns either an array or string.
  301. return $key == 'openssl' ? [] : '';
  302. }));
  303. $this->mapper->expects($this->once())
  304. ->method('insert');
  305. $this->secureRandom->expects($this->exactly(2))
  306. ->method('generate');
  307. $token = $this->subjectUnderTest->createTokens('user_agent');
  308. $this->assertTrue($token instanceof LoginFlowV2Tokens);
  309. }
  310. }