ContentSecurityPolicyManager.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Lukas Reschke <lukas@statuscode.ch>
  7. *
  8. * @license AGPL-3.0
  9. *
  10. * This code is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License, version 3,
  12. * as published by the Free Software Foundation.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU Affero General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Affero General Public License, version 3,
  20. * along with this program. If not, see <http://www.gnu.org/licenses/>
  21. *
  22. */
  23. namespace OC\Security\CSP;
  24. use OCP\AppFramework\Http\ContentSecurityPolicy;
  25. use OCP\AppFramework\Http\EmptyContentSecurityPolicy;
  26. use OCP\Security\IContentSecurityPolicyManager;
  27. class ContentSecurityPolicyManager implements IContentSecurityPolicyManager {
  28. /** @var ContentSecurityPolicy[] */
  29. private $policies = [];
  30. /** {@inheritdoc} */
  31. public function addDefaultPolicy(EmptyContentSecurityPolicy $policy) {
  32. $this->policies[] = $policy;
  33. }
  34. /**
  35. * Get the configured default policy. This is not in the public namespace
  36. * as it is only supposed to be used by core itself.
  37. *
  38. * @return ContentSecurityPolicy
  39. */
  40. public function getDefaultPolicy(): ContentSecurityPolicy {
  41. $defaultPolicy = new \OC\Security\CSP\ContentSecurityPolicy();
  42. foreach($this->policies as $policy) {
  43. $defaultPolicy = $this->mergePolicies($defaultPolicy, $policy);
  44. }
  45. return $defaultPolicy;
  46. }
  47. /**
  48. * Merges the first given policy with the second one
  49. *
  50. * @param ContentSecurityPolicy $defaultPolicy
  51. * @param EmptyContentSecurityPolicy $originalPolicy
  52. * @return ContentSecurityPolicy
  53. */
  54. public function mergePolicies(ContentSecurityPolicy $defaultPolicy,
  55. EmptyContentSecurityPolicy $originalPolicy): ContentSecurityPolicy {
  56. foreach((object)(array)$originalPolicy as $name => $value) {
  57. $setter = 'set'.ucfirst($name);
  58. if(\is_array($value)) {
  59. $getter = 'get'.ucfirst($name);
  60. $currentValues = \is_array($defaultPolicy->$getter()) ? $defaultPolicy->$getter() : [];
  61. $defaultPolicy->$setter(array_values(array_unique(array_merge($currentValues, $value))));
  62. } elseif (\is_bool($value)) {
  63. $defaultPolicy->$setter($value);
  64. }
  65. }
  66. return $defaultPolicy;
  67. }
  68. }