LoginFlowV2ServiceUnitTest.php 11 KB

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