ContentSecurityPolicyNonceManagerTest.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace Test\Security\CSP;
  8. use OC\AppFramework\Http\Request;
  9. use OC\Security\CSP\ContentSecurityPolicyNonceManager;
  10. use OC\Security\CSRF\CsrfToken;
  11. use OC\Security\CSRF\CsrfTokenManager;
  12. use PHPUnit\Framework\MockObject\MockObject;
  13. use Test\TestCase;
  14. class ContentSecurityPolicyNonceManagerTest extends TestCase {
  15. /** @var CsrfTokenManager&MockObject */
  16. private $CSRFTokenManager;
  17. /** @var Request&MockObject */
  18. private $request;
  19. /** @var ContentSecurityPolicyNonceManager */
  20. private $nonceManager;
  21. protected function setUp(): void {
  22. $this->CSRFTokenManager = $this->createMock(CsrfTokenManager::class);
  23. $this->request = $this->createMock(Request::class);
  24. $this->nonceManager = new ContentSecurityPolicyNonceManager(
  25. $this->CSRFTokenManager,
  26. $this->request
  27. );
  28. }
  29. public function testGetNonce(): void {
  30. $secret = base64_encode('secret');
  31. $tokenValue = base64_encode('secret' ^ 'value_') . ':' . $secret;
  32. $token = $this->createMock(CsrfToken::class);
  33. $token
  34. ->expects($this->once())
  35. ->method('getEncryptedValue')
  36. ->willReturn($tokenValue);
  37. $this->CSRFTokenManager
  38. ->expects($this->once())
  39. ->method('getToken')
  40. ->willReturn($token);
  41. $this->assertSame($secret, $this->nonceManager->getNonce());
  42. // call it twice but `getEncryptedValue` is expected to be called only once
  43. $this->assertSame($secret, $this->nonceManager->getNonce());
  44. }
  45. public function testGetNonceServerVar(): void {
  46. $token = 'SERVERNONCE';
  47. $this->request
  48. ->method('__isset')
  49. ->with('server')
  50. ->willReturn(true);
  51. $this->request
  52. ->method('__get')
  53. ->with('server')
  54. ->willReturn(['CSP_NONCE' => $token]);
  55. $this->assertSame($token, $this->nonceManager->getNonce());
  56. // call it twice but `CSP_NONCE` variable is expected to be loaded only once
  57. $this->assertSame($token, $this->nonceManager->getNonce());
  58. }
  59. }