CSRFTokenControllerTest.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace Tests\Core\Controller;
  7. use OC\Core\Controller\CSRFTokenController;
  8. use OC\Security\CSRF\CsrfToken;
  9. use OC\Security\CSRF\CsrfTokenManager;
  10. use OCP\AppFramework\Http;
  11. use OCP\AppFramework\Http\JSONResponse;
  12. use OCP\IRequest;
  13. use Test\TestCase;
  14. class CSRFTokenControllerTest extends TestCase {
  15. /** @var CSRFTokenController */
  16. private $controller;
  17. /** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */
  18. private $request;
  19. /** @var CsrfTokenManager|\PHPUnit\Framework\MockObject\MockObject */
  20. private $tokenManager;
  21. protected function setUp(): void {
  22. parent::setUp();
  23. $this->request = $this->createMock(IRequest::class);
  24. $this->tokenManager = $this->createMock(CsrfTokenManager::class);
  25. $this->controller = new CSRFTokenController('core', $this->request,
  26. $this->tokenManager);
  27. }
  28. public function testGetToken(): void {
  29. $this->request->method('passesStrictCookieCheck')->willReturn(true);
  30. $token = $this->createMock(CsrfToken::class);
  31. $this->tokenManager->method('getToken')->willReturn($token);
  32. $token->method('getEncryptedValue')->willReturn('toktok123');
  33. $response = $this->controller->index();
  34. $this->assertInstanceOf(JSONResponse::class, $response);
  35. $this->assertSame(Http::STATUS_OK, $response->getStatus());
  36. $this->assertEquals([
  37. 'token' => 'toktok123'
  38. ], $response->getData());
  39. }
  40. public function testGetTokenNoStrictSameSiteCookie(): void {
  41. $this->request->method('passesStrictCookieCheck')->willReturn(false);
  42. $response = $this->controller->index();
  43. $this->assertInstanceOf(JSONResponse::class, $response);
  44. $this->assertSame(Http::STATUS_FORBIDDEN, $response->getStatus());
  45. }
  46. }