ContentSecurityPolicyManager.php 2.4 KB

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