OauthApiControllerTest.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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 Test\TestCase;
  46. /* We have to use this to add a property to the mocked request and avoid warnings about dynamic properties on PHP>=8.2 */
  47. abstract class RequestMock implements IRequest {
  48. public array $server = [];
  49. }
  50. class OauthApiControllerTest extends TestCase {
  51. /** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */
  52. private $request;
  53. /** @var ICrypto|\PHPUnit\Framework\MockObject\MockObject */
  54. private $crypto;
  55. /** @var AccessTokenMapper|\PHPUnit\Framework\MockObject\MockObject */
  56. private $accessTokenMapper;
  57. /** @var ClientMapper|\PHPUnit\Framework\MockObject\MockObject */
  58. private $clientMapper;
  59. /** @var TokenProvider|\PHPUnit\Framework\MockObject\MockObject */
  60. private $tokenProvider;
  61. /** @var ISecureRandom|\PHPUnit\Framework\MockObject\MockObject */
  62. private $secureRandom;
  63. /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */
  64. private $time;
  65. /** @var Throttler|\PHPUnit\Framework\MockObject\MockObject */
  66. private $throttler;
  67. /** @var OauthApiController */
  68. private $oauthApiController;
  69. protected function setUp(): void {
  70. parent::setUp();
  71. $this->request = $this->createMock(RequestMock::class);
  72. $this->crypto = $this->createMock(ICrypto::class);
  73. $this->accessTokenMapper = $this->createMock(AccessTokenMapper::class);
  74. $this->clientMapper = $this->createMock(ClientMapper::class);
  75. $this->tokenProvider = $this->createMock(TokenProvider::class);
  76. $this->secureRandom = $this->createMock(ISecureRandom::class);
  77. $this->time = $this->createMock(ITimeFactory::class);
  78. $this->throttler = $this->createMock(Throttler::class);
  79. $this->oauthApiController = new OauthApiController(
  80. 'oauth2',
  81. $this->request,
  82. $this->crypto,
  83. $this->accessTokenMapper,
  84. $this->clientMapper,
  85. $this->tokenProvider,
  86. $this->secureRandom,
  87. $this->time,
  88. $this->throttler
  89. );
  90. }
  91. public function testGetTokenInvalidGrantType() {
  92. $expected = new JSONResponse([
  93. 'error' => 'invalid_grant',
  94. ], Http::STATUS_BAD_REQUEST);
  95. $this->assertEquals($expected, $this->oauthApiController->getToken('foo', null, null, null, null));
  96. }
  97. public function testGetTokenInvalidCode() {
  98. $expected = new JSONResponse([
  99. 'error' => 'invalid_request',
  100. ], Http::STATUS_BAD_REQUEST);
  101. $this->accessTokenMapper->method('getByCode')
  102. ->with('invalidcode')
  103. ->willThrowException(new AccessTokenNotFoundException());
  104. $this->assertEquals($expected, $this->oauthApiController->getToken('authorization_code', 'invalidcode', null, null, null));
  105. }
  106. public function testGetTokenInvalidRefreshToken() {
  107. $expected = new JSONResponse([
  108. 'error' => 'invalid_request',
  109. ], Http::STATUS_BAD_REQUEST);
  110. $this->accessTokenMapper->method('getByCode')
  111. ->with('invalidrefresh')
  112. ->willThrowException(new AccessTokenNotFoundException());
  113. $this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'invalidrefresh', null, null));
  114. }
  115. public function testGetTokenClientDoesNotExist() {
  116. $expected = new JSONResponse([
  117. 'error' => 'invalid_request',
  118. ], Http::STATUS_BAD_REQUEST);
  119. $accessToken = new AccessToken();
  120. $accessToken->setClientId(42);
  121. $this->accessTokenMapper->method('getByCode')
  122. ->with('validrefresh')
  123. ->willReturn($accessToken);
  124. $this->clientMapper->method('getByUid')
  125. ->with(42)
  126. ->willThrowException(new ClientNotFoundException());
  127. $this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', null, null));
  128. }
  129. public function invalidClientProvider() {
  130. return [
  131. ['invalidClientId', 'invalidClientSecret'],
  132. ['clientId', 'invalidClientSecret'],
  133. ['invalidClientId', 'clientSecret'],
  134. ];
  135. }
  136. /**
  137. * @dataProvider invalidClientProvider
  138. *
  139. * @param string $clientId
  140. * @param string $clientSecret
  141. */
  142. public function testGetTokenInvalidClient($clientId, $clientSecret) {
  143. $expected = new JSONResponse([
  144. 'error' => 'invalid_client',
  145. ], Http::STATUS_BAD_REQUEST);
  146. $accessToken = new AccessToken();
  147. $accessToken->setClientId(42);
  148. $this->accessTokenMapper->method('getByCode')
  149. ->with('validrefresh')
  150. ->willReturn($accessToken);
  151. $client = new Client();
  152. $client->setClientIdentifier('clientId');
  153. $client->setSecret('clientSecret');
  154. $this->clientMapper->method('getByUid')
  155. ->with(42)
  156. ->willReturn($client);
  157. $this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', $clientId, $clientSecret));
  158. }
  159. public function testGetTokenInvalidAppToken() {
  160. $expected = new JSONResponse([
  161. 'error' => 'invalid_request',
  162. ], Http::STATUS_BAD_REQUEST);
  163. $accessToken = new AccessToken();
  164. $accessToken->setClientId(42);
  165. $accessToken->setTokenId(1337);
  166. $accessToken->setEncryptedToken('encryptedToken');
  167. $this->accessTokenMapper->method('getByCode')
  168. ->with('validrefresh')
  169. ->willReturn($accessToken);
  170. $client = new Client();
  171. $client->setClientIdentifier('clientId');
  172. $client->setSecret('clientSecret');
  173. $this->clientMapper->method('getByUid')
  174. ->with(42)
  175. ->willReturn($client);
  176. $this->crypto->method('decrypt')
  177. ->with(
  178. 'encryptedToken',
  179. 'validrefresh'
  180. )->willReturn('decryptedToken');
  181. $this->tokenProvider->method('getTokenById')
  182. ->with(1337)
  183. ->willThrowException(new InvalidTokenException());
  184. $this->accessTokenMapper->expects($this->once())
  185. ->method('delete')
  186. ->with($accessToken);
  187. $this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', 'clientId', 'clientSecret'));
  188. }
  189. public function testGetTokenValidAppToken() {
  190. $accessToken = new AccessToken();
  191. $accessToken->setClientId(42);
  192. $accessToken->setTokenId(1337);
  193. $accessToken->setEncryptedToken('encryptedToken');
  194. $this->accessTokenMapper->method('getByCode')
  195. ->with('validrefresh')
  196. ->willReturn($accessToken);
  197. $client = new Client();
  198. $client->setClientIdentifier('clientId');
  199. $client->setSecret('clientSecret');
  200. $this->clientMapper->method('getByUid')
  201. ->with(42)
  202. ->willReturn($client);
  203. $this->crypto->method('decrypt')
  204. ->with(
  205. 'encryptedToken',
  206. 'validrefresh'
  207. )->willReturn('decryptedToken');
  208. $appToken = new PublicKeyToken();
  209. $appToken->setUid('userId');
  210. $this->tokenProvider->method('getTokenById')
  211. ->with(1337)
  212. ->willThrowException(new ExpiredTokenException($appToken));
  213. $this->accessTokenMapper->expects($this->never())
  214. ->method('delete')
  215. ->with($accessToken);
  216. $this->secureRandom->method('generate')
  217. ->willReturnCallback(function ($len) {
  218. return 'random'.$len;
  219. });
  220. $this->tokenProvider->expects($this->once())
  221. ->method('rotate')
  222. ->with(
  223. $appToken,
  224. 'decryptedToken',
  225. 'random72'
  226. )->willReturn($appToken);
  227. $this->time->method('getTime')
  228. ->willReturn(1000);
  229. $this->tokenProvider->expects($this->once())
  230. ->method('updateToken')
  231. ->with(
  232. $this->callback(function (PublicKeyToken $token) {
  233. return $token->getExpires() === 4600;
  234. })
  235. );
  236. $this->crypto->method('encrypt')
  237. ->with('random72', 'random128')
  238. ->willReturn('newEncryptedToken');
  239. $this->accessTokenMapper->expects($this->once())
  240. ->method('update')
  241. ->with(
  242. $this->callback(function (AccessToken $token) {
  243. return $token->getHashedCode() === hash('sha512', 'random128') &&
  244. $token->getEncryptedToken() === 'newEncryptedToken';
  245. })
  246. );
  247. $expected = new JSONResponse([
  248. 'access_token' => 'random72',
  249. 'token_type' => 'Bearer',
  250. 'expires_in' => 3600,
  251. 'refresh_token' => 'random128',
  252. 'user_id' => 'userId',
  253. ]);
  254. $this->request->method('getRemoteAddress')
  255. ->willReturn('1.2.3.4');
  256. $this->throttler->expects($this->once())
  257. ->method('resetDelay')
  258. ->with(
  259. '1.2.3.4',
  260. 'login',
  261. ['user' => 'userId']
  262. );
  263. $this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', 'clientId', 'clientSecret'));
  264. }
  265. public function testGetTokenValidAppTokenBasicAuth() {
  266. $accessToken = new AccessToken();
  267. $accessToken->setClientId(42);
  268. $accessToken->setTokenId(1337);
  269. $accessToken->setEncryptedToken('encryptedToken');
  270. $this->accessTokenMapper->method('getByCode')
  271. ->with('validrefresh')
  272. ->willReturn($accessToken);
  273. $client = new Client();
  274. $client->setClientIdentifier('clientId');
  275. $client->setSecret('clientSecret');
  276. $this->clientMapper->method('getByUid')
  277. ->with(42)
  278. ->willReturn($client);
  279. $this->crypto->method('decrypt')
  280. ->with(
  281. 'encryptedToken',
  282. 'validrefresh'
  283. )->willReturn('decryptedToken');
  284. $appToken = new PublicKeyToken();
  285. $appToken->setUid('userId');
  286. $this->tokenProvider->method('getTokenById')
  287. ->with(1337)
  288. ->willThrowException(new ExpiredTokenException($appToken));
  289. $this->accessTokenMapper->expects($this->never())
  290. ->method('delete')
  291. ->with($accessToken);
  292. $this->secureRandom->method('generate')
  293. ->willReturnCallback(function ($len) {
  294. return 'random'.$len;
  295. });
  296. $this->tokenProvider->expects($this->once())
  297. ->method('rotate')
  298. ->with(
  299. $appToken,
  300. 'decryptedToken',
  301. 'random72'
  302. )->willReturn($appToken);
  303. $this->time->method('getTime')
  304. ->willReturn(1000);
  305. $this->tokenProvider->expects($this->once())
  306. ->method('updateToken')
  307. ->with(
  308. $this->callback(function (PublicKeyToken $token) {
  309. return $token->getExpires() === 4600;
  310. })
  311. );
  312. $this->crypto->method('encrypt')
  313. ->with('random72', 'random128')
  314. ->willReturn('newEncryptedToken');
  315. $this->accessTokenMapper->expects($this->once())
  316. ->method('update')
  317. ->with(
  318. $this->callback(function (AccessToken $token) {
  319. return $token->getHashedCode() === hash('sha512', 'random128') &&
  320. $token->getEncryptedToken() === 'newEncryptedToken';
  321. })
  322. );
  323. $expected = new JSONResponse([
  324. 'access_token' => 'random72',
  325. 'token_type' => 'Bearer',
  326. 'expires_in' => 3600,
  327. 'refresh_token' => 'random128',
  328. 'user_id' => 'userId',
  329. ]);
  330. $this->request->server['PHP_AUTH_USER'] = 'clientId';
  331. $this->request->server['PHP_AUTH_PW'] = 'clientSecret';
  332. $this->request->method('getRemoteAddress')
  333. ->willReturn('1.2.3.4');
  334. $this->throttler->expects($this->once())
  335. ->method('resetDelay')
  336. ->with(
  337. '1.2.3.4',
  338. 'login',
  339. ['user' => 'userId']
  340. );
  341. $this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', null, null));
  342. }
  343. public function testGetTokenExpiredAppToken() {
  344. $accessToken = new AccessToken();
  345. $accessToken->setClientId(42);
  346. $accessToken->setTokenId(1337);
  347. $accessToken->setEncryptedToken('encryptedToken');
  348. $this->accessTokenMapper->method('getByCode')
  349. ->with('validrefresh')
  350. ->willReturn($accessToken);
  351. $client = new Client();
  352. $client->setClientIdentifier('clientId');
  353. $client->setSecret('clientSecret');
  354. $this->clientMapper->method('getByUid')
  355. ->with(42)
  356. ->willReturn($client);
  357. $this->crypto->method('decrypt')
  358. ->with(
  359. 'encryptedToken',
  360. 'validrefresh'
  361. )->willReturn('decryptedToken');
  362. $appToken = new PublicKeyToken();
  363. $appToken->setUid('userId');
  364. $this->tokenProvider->method('getTokenById')
  365. ->with(1337)
  366. ->willReturn($appToken);
  367. $this->accessTokenMapper->expects($this->never())
  368. ->method('delete')
  369. ->with($accessToken);
  370. $this->secureRandom->method('generate')
  371. ->willReturnCallback(function ($len) {
  372. return 'random'.$len;
  373. });
  374. $this->tokenProvider->expects($this->once())
  375. ->method('rotate')
  376. ->with(
  377. $appToken,
  378. 'decryptedToken',
  379. 'random72'
  380. )->willReturn($appToken);
  381. $this->time->method('getTime')
  382. ->willReturn(1000);
  383. $this->tokenProvider->expects($this->once())
  384. ->method('updateToken')
  385. ->with(
  386. $this->callback(function (PublicKeyToken $token) {
  387. return $token->getExpires() === 4600;
  388. })
  389. );
  390. $this->crypto->method('encrypt')
  391. ->with('random72', 'random128')
  392. ->willReturn('newEncryptedToken');
  393. $this->accessTokenMapper->expects($this->once())
  394. ->method('update')
  395. ->with(
  396. $this->callback(function (AccessToken $token) {
  397. return $token->getHashedCode() === hash('sha512', 'random128') &&
  398. $token->getEncryptedToken() === 'newEncryptedToken';
  399. })
  400. );
  401. $expected = new JSONResponse([
  402. 'access_token' => 'random72',
  403. 'token_type' => 'Bearer',
  404. 'expires_in' => 3600,
  405. 'refresh_token' => 'random128',
  406. 'user_id' => 'userId',
  407. ]);
  408. $this->request->method('getRemoteAddress')
  409. ->willReturn('1.2.3.4');
  410. $this->throttler->expects($this->once())
  411. ->method('resetDelay')
  412. ->with(
  413. '1.2.3.4',
  414. 'login',
  415. ['user' => 'userId']
  416. );
  417. $this->assertEquals($expected, $this->oauthApiController->getToken('refresh_token', null, 'validrefresh', 'clientId', 'clientSecret'));
  418. }
  419. }