OauthApiControllerTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch>
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Lukas Reschke <lukas@statuscode.ch>
  7. * @author Morris Jobke <hey@morrisjobke.de>
  8. * @author Roeland Jago Douma <roeland@famdouma.nl>
  9. *
  10. * @license GNU AGPL version 3 or any later version
  11. *
  12. * This program is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU Affero General Public License as
  14. * published by the Free Software Foundation, either version 3 of the
  15. * License, or (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. *
  25. */
  26. namespace OCA\OAuth2\Tests\Controller;
  27. use OC\Authentication\Exceptions\ExpiredTokenException;
  28. use OC\Authentication\Exceptions\InvalidTokenException;
  29. use OC\Authentication\Token\IProvider as TokenProvider;
  30. use OC\Authentication\Token\PublicKeyToken;
  31. use OC\Security\Bruteforce\Throttler;
  32. use OCA\OAuth2\Controller\OauthApiController;
  33. use OCA\OAuth2\Db\AccessToken;
  34. use OCA\OAuth2\Db\AccessTokenMapper;
  35. use OCA\OAuth2\Db\Client;
  36. use OCA\OAuth2\Db\ClientMapper;
  37. use OCA\OAuth2\Exceptions\AccessTokenNotFoundException;
  38. use OCA\OAuth2\Exceptions\ClientNotFoundException;
  39. use OCP\AppFramework\Http;
  40. use OCP\AppFramework\Http\JSONResponse;
  41. use OCP\AppFramework\Utility\ITimeFactory;
  42. use OCP\IRequest;
  43. use OCP\Security\ICrypto;
  44. use OCP\Security\ISecureRandom;
  45. use Psr\Log\LoggerInterface;
  46. use Test\TestCase;
  47. /* We have to use this to add a property to the mocked request and avoid warnings about dynamic properties on PHP>=8.2 */
  48. abstract class RequestMock implements IRequest {
  49. public array $server = [];
  50. }
  51. class OauthApiControllerTest extends TestCase {
  52. /** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */
  53. private $request;
  54. /** @var ICrypto|\PHPUnit\Framework\MockObject\MockObject */
  55. private $crypto;
  56. /** @var AccessTokenMapper|\PHPUnit\Framework\MockObject\MockObject */
  57. private $accessTokenMapper;
  58. /** @var ClientMapper|\PHPUnit\Framework\MockObject\MockObject */
  59. private $clientMapper;
  60. /** @var TokenProvider|\PHPUnit\Framework\MockObject\MockObject */
  61. private $tokenProvider;
  62. /** @var ISecureRandom|\PHPUnit\Framework\MockObject\MockObject */
  63. private $secureRandom;
  64. /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */
  65. private $timeFactory;
  66. /** @var Throttler|\PHPUnit\Framework\MockObject\MockObject */
  67. private $throttler;
  68. /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */
  69. private $logger;
  70. /** @var OauthApiController */
  71. private $oauthApiController;
  72. protected function setUp(): void {
  73. parent::setUp();
  74. $this->request = $this->createMock(RequestMock::class);
  75. $this->crypto = $this->createMock(ICrypto::class);
  76. $this->accessTokenMapper = $this->createMock(AccessTokenMapper::class);
  77. $this->clientMapper = $this->createMock(ClientMapper::class);
  78. $this->tokenProvider = $this->createMock(TokenProvider::class);
  79. $this->secureRandom = $this->createMock(ISecureRandom::class);
  80. $this->timeFactory = $this->createMock(ITimeFactory::class);
  81. $this->throttler = $this->createMock(Throttler::class);
  82. $this->logger = $this->createMock(LoggerInterface::class);
  83. $this->oauthApiController = new OauthApiController(
  84. 'oauth2',
  85. $this->request,
  86. $this->crypto,
  87. $this->accessTokenMapper,
  88. $this->clientMapper,
  89. $this->tokenProvider,
  90. $this->secureRandom,
  91. $this->timeFactory,
  92. $this->logger,
  93. $this->throttler,
  94. );
  95. }
  96. public function testGetTokenInvalidGrantType() {
  97. $expected = new JSONResponse([
  98. 'error' => 'invalid_grant',
  99. ], Http::STATUS_BAD_REQUEST);
  100. $expected->throttle(['invalid_grant' => 'foo']);
  101. $this->assertEquals($expected, $this->oauthApiController->getToken('foo', null, null, null, null));
  102. }
  103. public function testGetTokenInvalidCode() {
  104. $expected = new JSONResponse([
  105. 'error' => 'invalid_request',
  106. ], Http::STATUS_BAD_REQUEST);
  107. $expected->throttle(['invalid_request' => 'token not found', 'code' => 'invalidcode']);
  108. $this->accessTokenMapper->method('getByCode')
  109. ->with('invalidcode')
  110. ->willThrowException(new AccessTokenNotFoundException());
  111. $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'invalidcode', null, null, null));
  112. }
  113. public function testGetTokenExpiredCode() {
  114. $codeCreatedAt = 100;
  115. $expiredSince = 123;
  116. $expected = new JSONResponse([
  117. 'error' => 'invalid_request',
  118. ], Http::STATUS_BAD_REQUEST);
  119. $expected->throttle(['invalid_request' => 'authorization_code_expired', 'expired_since' => $expiredSince]);
  120. $accessToken = new AccessToken();
  121. $accessToken->setClientId(42);
  122. $accessToken->setCodeCreatedAt($codeCreatedAt);
  123. $this->accessTokenMapper->method('getByCode')
  124. ->with('validcode')
  125. ->willReturn($accessToken);
  126. $tsNow = $codeCreatedAt + OauthApiController::AUTHORIZATION_CODE_EXPIRES_AFTER + $expiredSince;
  127. $dateNow = (new \DateTimeImmutable())->setTimestamp($tsNow);
  128. $this->timeFactory->method('now')
  129. ->willReturn($dateNow);
  130. $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, null, null));
  131. }
  132. public function testGetTokenWithCodeForActiveToken() {
  133. // if a token has already delivered oauth tokens,
  134. // it should not be possible to get a new oauth token from a valid authorization code
  135. $codeCreatedAt = 100;
  136. $expected = new JSONResponse([
  137. 'error' => 'invalid_request',
  138. ], Http::STATUS_BAD_REQUEST);
  139. $expected->throttle(['invalid_request' => 'authorization_code_received_for_active_token']);
  140. $accessToken = new AccessToken();
  141. $accessToken->setClientId(42);
  142. $accessToken->setCodeCreatedAt($codeCreatedAt);
  143. $accessToken->setTokenCount(1);
  144. $this->accessTokenMapper->method('getByCode')
  145. ->with('validcode')
  146. ->willReturn($accessToken);
  147. $tsNow = $codeCreatedAt + 1;
  148. $dateNow = (new \DateTimeImmutable())->setTimestamp($tsNow);
  149. $this->timeFactory->method('now')
  150. ->willReturn($dateNow);
  151. $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, null, null));
  152. }
  153. public function testGetTokenClientDoesNotExist() {
  154. // In this test, the token's authorization code is valid and has not expired
  155. // and we check what happens when the associated Oauth client does not exist
  156. $codeCreatedAt = 100;
  157. $expected = new JSONResponse([
  158. 'error' => 'invalid_request',
  159. ], Http::STATUS_BAD_REQUEST);
  160. $expected->throttle(['invalid_request' => 'client not found', 'client_id' => 42]);
  161. $accessToken = new AccessToken();
  162. $accessToken->setClientId(42);
  163. $accessToken->setCodeCreatedAt($codeCreatedAt);
  164. $this->accessTokenMapper->method('getByCode')
  165. ->with('validcode')
  166. ->willReturn($accessToken);
  167. // 'now' is before the token's authorization code expiration
  168. $tsNow = $codeCreatedAt + OauthApiController::AUTHORIZATION_CODE_EXPIRES_AFTER - 1;
  169. $dateNow = (new \DateTimeImmutable())->setTimestamp($tsNow);
  170. $this->timeFactory->method('now')
  171. ->willReturn($dateNow);
  172. $this->clientMapper->method('getByUid')
  173. ->with(42)
  174. ->willThrowException(new ClientNotFoundException());
  175. $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'validcode', null, null, null));
  176. }
  177. public function testRefreshTokenInvalidRefreshToken() {
  178. $expected = new JSONResponse([
  179. 'error' => 'invalid_request',
  180. ], Http::STATUS_BAD_REQUEST);
  181. $expected->throttle(['invalid_request' => 'token not found', 'code' => 'invalidrefresh']);
  182. $this->accessTokenMapper->method('getByCode')
  183. ->with('invalidrefresh')
  184. ->willThrowException(new AccessTokenNotFoundException());
  185. $this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'invalidrefresh', null, null));
  186. }
  187. public function testRefreshTokenClientDoesNotExist() {
  188. $expected = new JSONResponse([
  189. 'error' => 'invalid_request',
  190. ], Http::STATUS_BAD_REQUEST);
  191. $expected->throttle(['invalid_request' => 'client not found', 'client_id' => 42]);
  192. $accessToken = new AccessToken();
  193. $accessToken->setClientId(42);
  194. $this->accessTokenMapper->method('getByCode')
  195. ->with('validrefresh')
  196. ->willReturn($accessToken);
  197. $this->clientMapper->method('getByUid')
  198. ->with(42)
  199. ->willThrowException(new ClientNotFoundException());
  200. $this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', null, null));
  201. }
  202. public function invalidClientProvider() {
  203. return [
  204. ['invalidClientId', 'invalidClientSecret'],
  205. ['clientId', 'invalidClientSecret'],
  206. ['invalidClientId', 'clientSecret'],
  207. ];
  208. }
  209. /**
  210. * @dataProvider invalidClientProvider
  211. *
  212. * @param string $clientId
  213. * @param string $clientSecret
  214. */
  215. public function testRefreshTokenInvalidClient($clientId, $clientSecret) {
  216. $expected = new JSONResponse([
  217. 'error' => 'invalid_client',
  218. ], Http::STATUS_BAD_REQUEST);
  219. $expected->throttle(['invalid_client' => 'client ID or secret does not match']);
  220. $accessToken = new AccessToken();
  221. $accessToken->setClientId(42);
  222. $this->accessTokenMapper->method('getByCode')
  223. ->with('validrefresh')
  224. ->willReturn($accessToken);
  225. $client = new Client();
  226. $client->setClientIdentifier('clientId');
  227. $client->setSecret('clientSecret');
  228. $this->clientMapper->method('getByUid')
  229. ->with(42)
  230. ->willReturn($client);
  231. $this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', $clientId, $clientSecret));
  232. }
  233. public function testRefreshTokenInvalidAppToken() {
  234. $expected = new JSONResponse([
  235. 'error' => 'invalid_request',
  236. ], Http::STATUS_BAD_REQUEST);
  237. $expected->throttle(['invalid_request' => 'token is invalid']);
  238. $accessToken = new AccessToken();
  239. $accessToken->setClientId(42);
  240. $accessToken->setTokenId(1337);
  241. $accessToken->setEncryptedToken('encryptedToken');
  242. $this->accessTokenMapper->method('getByCode')
  243. ->with('validrefresh')
  244. ->willReturn($accessToken);
  245. $client = new Client();
  246. $client->setClientIdentifier('clientId');
  247. $client->setSecret('encryptedClientSecret');
  248. $this->clientMapper->method('getByUid')
  249. ->with(42)
  250. ->willReturn($client);
  251. $this->crypto
  252. ->method('decrypt')
  253. ->with($this->callback(function (string $text) {
  254. return $text === 'encryptedClientSecret' || $text === 'encryptedToken';
  255. }))
  256. ->willReturnCallback(function (string $text) {
  257. return $text === 'encryptedClientSecret'
  258. ? 'clientSecret'
  259. : ($text === 'encryptedToken' ? 'decryptedToken' : '');
  260. });
  261. $this->tokenProvider->method('getTokenById')
  262. ->with(1337)
  263. ->willThrowException(new InvalidTokenException());
  264. $this->accessTokenMapper->expects($this->once())
  265. ->method('delete')
  266. ->with($accessToken);
  267. $this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', 'clientId', 'clientSecret'));
  268. }
  269. public function testRefreshTokenValidAppToken() {
  270. $accessToken = new AccessToken();
  271. $accessToken->setClientId(42);
  272. $accessToken->setTokenId(1337);
  273. $accessToken->setEncryptedToken('encryptedToken');
  274. $this->accessTokenMapper->method('getByCode')
  275. ->with('validrefresh')
  276. ->willReturn($accessToken);
  277. $client = new Client();
  278. $client->setClientIdentifier('clientId');
  279. $client->setSecret('encryptedClientSecret');
  280. $this->clientMapper->method('getByUid')
  281. ->with(42)
  282. ->willReturn($client);
  283. $this->crypto
  284. ->method('decrypt')
  285. ->with($this->callback(function (string $text) {
  286. return $text === 'encryptedClientSecret' || $text === 'encryptedToken';
  287. }))
  288. ->willReturnCallback(function (string $text) {
  289. return $text === 'encryptedClientSecret'
  290. ? 'clientSecret'
  291. : ($text === 'encryptedToken' ? 'decryptedToken' : '');
  292. });
  293. $appToken = new PublicKeyToken();
  294. $appToken->setUid('userId');
  295. $this->tokenProvider->method('getTokenById')
  296. ->with(1337)
  297. ->willThrowException(new ExpiredTokenException($appToken));
  298. $this->accessTokenMapper->expects($this->never())
  299. ->method('delete')
  300. ->with($accessToken);
  301. $this->secureRandom->method('generate')
  302. ->willReturnCallback(function ($len) {
  303. return 'random'.$len;
  304. });
  305. $this->tokenProvider->expects($this->once())
  306. ->method('rotate')
  307. ->with(
  308. $appToken,
  309. 'decryptedToken',
  310. 'random72'
  311. )->willReturn($appToken);
  312. $this->timeFactory->method('getTime')
  313. ->willReturn(1000);
  314. $this->tokenProvider->expects($this->once())
  315. ->method('updateToken')
  316. ->with(
  317. $this->callback(function (PublicKeyToken $token) {
  318. return $token->getExpires() === 4600;
  319. })
  320. );
  321. $this->crypto->method('encrypt')
  322. ->with('random72', 'random128')
  323. ->willReturn('newEncryptedToken');
  324. $this->accessTokenMapper->expects($this->once())
  325. ->method('update')
  326. ->with(
  327. $this->callback(function (AccessToken $token) {
  328. return $token->getHashedCode() === hash('sha512', 'random128') &&
  329. $token->getEncryptedToken() === 'newEncryptedToken';
  330. })
  331. );
  332. $expected = new JSONResponse([
  333. 'access_token' => 'random72',
  334. 'token_type' => 'Bearer',
  335. 'expires_in' => 3600,
  336. 'refresh_token' => 'random128',
  337. 'user_id' => 'userId',
  338. ]);
  339. $this->request->method('getRemoteAddress')
  340. ->willReturn('1.2.3.4');
  341. $this->throttler->expects($this->once())
  342. ->method('resetDelay')
  343. ->with(
  344. '1.2.3.4',
  345. 'login',
  346. ['user' => 'userId']
  347. );
  348. $this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', 'clientId', 'clientSecret'));
  349. }
  350. public function testRefreshTokenValidAppTokenBasicAuth() {
  351. $accessToken = new AccessToken();
  352. $accessToken->setClientId(42);
  353. $accessToken->setTokenId(1337);
  354. $accessToken->setEncryptedToken('encryptedToken');
  355. $this->accessTokenMapper->method('getByCode')
  356. ->with('validrefresh')
  357. ->willReturn($accessToken);
  358. $client = new Client();
  359. $client->setClientIdentifier('clientId');
  360. $client->setSecret('encryptedClientSecret');
  361. $this->clientMapper->method('getByUid')
  362. ->with(42)
  363. ->willReturn($client);
  364. $this->crypto
  365. ->method('decrypt')
  366. ->with($this->callback(function (string $text) {
  367. return $text === 'encryptedClientSecret' || $text === 'encryptedToken';
  368. }))
  369. ->willReturnCallback(function (string $text) {
  370. return $text === 'encryptedClientSecret'
  371. ? 'clientSecret'
  372. : ($text === 'encryptedToken' ? 'decryptedToken' : '');
  373. });
  374. $appToken = new PublicKeyToken();
  375. $appToken->setUid('userId');
  376. $this->tokenProvider->method('getTokenById')
  377. ->with(1337)
  378. ->willThrowException(new ExpiredTokenException($appToken));
  379. $this->accessTokenMapper->expects($this->never())
  380. ->method('delete')
  381. ->with($accessToken);
  382. $this->secureRandom->method('generate')
  383. ->willReturnCallback(function ($len) {
  384. return 'random'.$len;
  385. });
  386. $this->tokenProvider->expects($this->once())
  387. ->method('rotate')
  388. ->with(
  389. $appToken,
  390. 'decryptedToken',
  391. 'random72'
  392. )->willReturn($appToken);
  393. $this->timeFactory->method('getTime')
  394. ->willReturn(1000);
  395. $this->tokenProvider->expects($this->once())
  396. ->method('updateToken')
  397. ->with(
  398. $this->callback(function (PublicKeyToken $token) {
  399. return $token->getExpires() === 4600;
  400. })
  401. );
  402. $this->crypto->method('encrypt')
  403. ->with('random72', 'random128')
  404. ->willReturn('newEncryptedToken');
  405. $this->accessTokenMapper->expects($this->once())
  406. ->method('update')
  407. ->with(
  408. $this->callback(function (AccessToken $token) {
  409. return $token->getHashedCode() === hash('sha512', 'random128') &&
  410. $token->getEncryptedToken() === 'newEncryptedToken';
  411. })
  412. );
  413. $expected = new JSONResponse([
  414. 'access_token' => 'random72',
  415. 'token_type' => 'Bearer',
  416. 'expires_in' => 3600,
  417. 'refresh_token' => 'random128',
  418. 'user_id' => 'userId',
  419. ]);
  420. $this->request->server['PHP_AUTH_USER'] = 'clientId';
  421. $this->request->server['PHP_AUTH_PW'] = 'clientSecret';
  422. $this->request->method('getRemoteAddress')
  423. ->willReturn('1.2.3.4');
  424. $this->throttler->expects($this->once())
  425. ->method('resetDelay')
  426. ->with(
  427. '1.2.3.4',
  428. 'login',
  429. ['user' => 'userId']
  430. );
  431. $this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', null, null));
  432. }
  433. public function testRefreshTokenExpiredAppToken() {
  434. $accessToken = new AccessToken();
  435. $accessToken->setClientId(42);
  436. $accessToken->setTokenId(1337);
  437. $accessToken->setEncryptedToken('encryptedToken');
  438. $this->accessTokenMapper->method('getByCode')
  439. ->with('validrefresh')
  440. ->willReturn($accessToken);
  441. $client = new Client();
  442. $client->setClientIdentifier('clientId');
  443. $client->setSecret('encryptedClientSecret');
  444. $this->clientMapper->method('getByUid')
  445. ->with(42)
  446. ->willReturn($client);
  447. $this->crypto
  448. ->method('decrypt')
  449. ->with($this->callback(function (string $text) {
  450. return $text === 'encryptedClientSecret' || $text === 'encryptedToken';
  451. }))
  452. ->willReturnCallback(function (string $text) {
  453. return $text === 'encryptedClientSecret'
  454. ? 'clientSecret'
  455. : ($text === 'encryptedToken' ? 'decryptedToken' : '');
  456. });
  457. $appToken = new PublicKeyToken();
  458. $appToken->setUid('userId');
  459. $this->tokenProvider->method('getTokenById')
  460. ->with(1337)
  461. ->willReturn($appToken);
  462. $this->accessTokenMapper->expects($this->never())
  463. ->method('delete')
  464. ->with($accessToken);
  465. $this->secureRandom->method('generate')
  466. ->willReturnCallback(function ($len) {
  467. return 'random'.$len;
  468. });
  469. $this->tokenProvider->expects($this->once())
  470. ->method('rotate')
  471. ->with(
  472. $appToken,
  473. 'decryptedToken',
  474. 'random72'
  475. )->willReturn($appToken);
  476. $this->timeFactory->method('getTime')
  477. ->willReturn(1000);
  478. $this->tokenProvider->expects($this->once())
  479. ->method('updateToken')
  480. ->with(
  481. $this->callback(function (PublicKeyToken $token) {
  482. return $token->getExpires() === 4600;
  483. })
  484. );
  485. $this->crypto->method('encrypt')
  486. ->with('random72', 'random128')
  487. ->willReturn('newEncryptedToken');
  488. $this->accessTokenMapper->expects($this->once())
  489. ->method('update')
  490. ->with(
  491. $this->callback(function (AccessToken $token) {
  492. return $token->getHashedCode() === hash('sha512', 'random128') &&
  493. $token->getEncryptedToken() === 'newEncryptedToken';
  494. })
  495. );
  496. $expected = new JSONResponse([
  497. 'access_token' => 'random72',
  498. 'token_type' => 'Bearer',
  499. 'expires_in' => 3600,
  500. 'refresh_token' => 'random128',
  501. 'user_id' => 'userId',
  502. ]);
  503. $this->request->method('getRemoteAddress')
  504. ->willReturn('1.2.3.4');
  505. $this->throttler->expects($this->once())
  506. ->method('resetDelay')
  507. ->with(
  508. '1.2.3.4',
  509. 'login',
  510. ['user' => 'userId']
  511. );
  512. $this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', 'clientId', 'clientSecret'));
  513. }
  514. }