FeaturePolicyMiddlewareTest.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace Test\AppFramework\Middleware\Security;
  8. use OC\AppFramework\Middleware\Security\FeaturePolicyMiddleware;
  9. use OC\Security\FeaturePolicy\FeaturePolicy;
  10. use OC\Security\FeaturePolicy\FeaturePolicyManager;
  11. use OCP\AppFramework\Controller;
  12. use OCP\AppFramework\Http\EmptyFeaturePolicy;
  13. use OCP\AppFramework\Http\Response;
  14. use PHPUnit\Framework\MockObject\MockObject;
  15. class FeaturePolicyMiddlewareTest extends \Test\TestCase {
  16. /** @var FeaturePolicyMiddleware|MockObject */
  17. private $middleware;
  18. /** @var Controller|MockObject */
  19. private $controller;
  20. /** @var FeaturePolicyManager|MockObject */
  21. private $manager;
  22. protected function setUp(): void {
  23. parent::setUp();
  24. $this->controller = $this->createMock(Controller::class);
  25. $this->manager = $this->createMock(FeaturePolicyManager::class);
  26. $this->middleware = new FeaturePolicyMiddleware(
  27. $this->manager
  28. );
  29. }
  30. public function testAfterController(): void {
  31. $response = $this->createMock(Response::class);
  32. $defaultPolicy = new FeaturePolicy();
  33. $defaultPolicy->addAllowedCameraDomain('defaultpolicy');
  34. $currentPolicy = new FeaturePolicy();
  35. $currentPolicy->addAllowedAutoplayDomain('currentPolicy');
  36. $mergedPolicy = new FeaturePolicy();
  37. $mergedPolicy->addAllowedGeoLocationDomain('mergedPolicy');
  38. $response->method('getFeaturePolicy')
  39. ->willReturn($currentPolicy);
  40. $this->manager->method('getDefaultPolicy')
  41. ->willReturn($defaultPolicy);
  42. $this->manager->method('mergePolicies')
  43. ->with($defaultPolicy, $currentPolicy)
  44. ->willReturn($mergedPolicy);
  45. $response->expects($this->once())
  46. ->method('setFeaturePolicy')
  47. ->with($mergedPolicy);
  48. $this->middleware->afterController($this->controller, 'test', $response);
  49. }
  50. public function testAfterControllerEmptyCSP(): void {
  51. $response = $this->createMock(Response::class);
  52. $emptyPolicy = new EmptyFeaturePolicy();
  53. $response->method('getFeaturePolicy')
  54. ->willReturn($emptyPolicy);
  55. $response->expects($this->never())
  56. ->method('setFeaturePolicy');
  57. $this->middleware->afterController($this->controller, 'test', $response);
  58. }
  59. }