ContentSecurityPolicyManager.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. }