SecurityHeadersTest.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2024 Côme Chilliet <come.chilliet@nextcloud.com>
  5. *
  6. * @author Côme Chilliet <come.chilliet@nextcloud.com>
  7. *
  8. * @license AGPL-3.0-or-later
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as
  12. * published by the Free Software Foundation, either version 3 of the
  13. * License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. */
  24. namespace OCA\Settings\Tests;
  25. use OCA\Settings\SetupChecks\SecurityHeaders;
  26. use OCP\Http\Client\IClientService;
  27. use OCP\Http\Client\IResponse;
  28. use OCP\IConfig;
  29. use OCP\IL10N;
  30. use OCP\IURLGenerator;
  31. use OCP\SetupCheck\SetupResult;
  32. use PHPUnit\Framework\MockObject\MockObject;
  33. use Psr\Log\LoggerInterface;
  34. use Test\TestCase;
  35. class SecurityHeadersTest extends TestCase {
  36. private IL10N|MockObject $l10n;
  37. private IConfig|MockObject $config;
  38. private IURLGenerator|MockObject $urlGenerator;
  39. private IClientService|MockObject $clientService;
  40. private LoggerInterface|MockObject $logger;
  41. private SecurityHeaders|MockObject $setupcheck;
  42. protected function setUp(): void {
  43. parent::setUp();
  44. /** @var IL10N|MockObject */
  45. $this->l10n = $this->getMockBuilder(IL10N::class)
  46. ->disableOriginalConstructor()->getMock();
  47. $this->l10n->expects($this->any())
  48. ->method('t')
  49. ->willReturnCallback(function ($message, array $replace) {
  50. return vsprintf($message, $replace);
  51. });
  52. $this->config = $this->createMock(IConfig::class);
  53. $this->urlGenerator = $this->createMock(IURLGenerator::class);
  54. $this->clientService = $this->createMock(IClientService::class);
  55. $this->logger = $this->createMock(LoggerInterface::class);
  56. $this->setupcheck = $this->getMockBuilder(SecurityHeaders::class)
  57. ->onlyMethods(['runRequest'])
  58. ->setConstructorArgs([
  59. $this->l10n,
  60. $this->config,
  61. $this->urlGenerator,
  62. $this->clientService,
  63. $this->logger,
  64. ])
  65. ->getMock();
  66. }
  67. public function testInvalidStatusCode(): void {
  68. $this->setupResponse(500, []);
  69. $result = $this->setupcheck->run();
  70. $this->assertMatchesRegularExpression('/^Could not check that your web server serves security headers correctly/', $result->getDescription());
  71. $this->assertEquals(SetupResult::WARNING, $result->getSeverity());
  72. }
  73. public function testAllHeadersMissing(): void {
  74. $this->setupResponse(200, []);
  75. $result = $this->setupcheck->run();
  76. $this->assertMatchesRegularExpression('/^Some headers are not set correctly on your instance/', $result->getDescription());
  77. $this->assertEquals(SetupResult::WARNING, $result->getSeverity());
  78. }
  79. public function testSomeHeadersMissing(): void {
  80. $this->setupResponse(
  81. 200,
  82. [
  83. 'X-Robots-Tag' => 'noindex, nofollow',
  84. 'X-Frame-Options' => 'SAMEORIGIN',
  85. 'Strict-Transport-Security' => 'max-age=15768000;preload',
  86. 'X-Permitted-Cross-Domain-Policies' => 'none',
  87. 'Referrer-Policy' => 'no-referrer',
  88. ]
  89. );
  90. $result = $this->setupcheck->run();
  91. $this->assertEquals(
  92. "Some headers are not set correctly on your instance\n- The `X-Content-Type-Options` HTTP header is not set to `nosniff`. This is a potential security or privacy risk, as it is recommended to adjust this setting accordingly.\n- The `X-XSS-Protection` HTTP header does not contain `1; mode=block`. This is a potential security or privacy risk, as it is recommended to adjust this setting accordingly.\n",
  93. $result->getDescription()
  94. );
  95. $this->assertEquals(SetupResult::WARNING, $result->getSeverity());
  96. }
  97. public function dataSuccess(): array {
  98. return [
  99. // description => modifiedHeaders
  100. 'basic' => [[]],
  101. 'extra-xss-protection' => [['X-XSS-Protection' => '1; mode=block; report=https://example.com']],
  102. 'no-space-in-x-robots' => [['X-Robots-Tag' => 'noindex,nofollow']],
  103. 'strict-origin-when-cross-origin' => [['Referrer-Policy' => 'strict-origin-when-cross-origin']],
  104. 'referrer-no-referrer-when-downgrade' => [['Referrer-Policy' => 'no-referrer-when-downgrade']],
  105. 'referrer-strict-origin' => [['Referrer-Policy' => 'strict-origin']],
  106. 'referrer-strict-origin-when-cross-origin' => [['Referrer-Policy' => 'strict-origin-when-cross-origin']],
  107. 'referrer-same-origin' => [['Referrer-Policy' => 'same-origin']],
  108. 'hsts-minimum' => [['Strict-Transport-Security' => 'max-age=15552000']],
  109. 'hsts-include-subdomains' => [['Strict-Transport-Security' => 'max-age=99999999; includeSubDomains']],
  110. 'hsts-include-subdomains-preload' => [['Strict-Transport-Security' => 'max-age=99999999; preload; includeSubDomains']],
  111. ];
  112. }
  113. /**
  114. * @dataProvider dataSuccess
  115. */
  116. public function testSuccess($headers): void {
  117. $headers = array_merge(
  118. [
  119. 'X-XSS-Protection' => '1; mode=block',
  120. 'X-Content-Type-Options' => 'nosniff',
  121. 'X-Robots-Tag' => 'noindex, nofollow',
  122. 'X-Frame-Options' => 'SAMEORIGIN',
  123. 'Strict-Transport-Security' => 'max-age=15768000',
  124. 'X-Permitted-Cross-Domain-Policies' => 'none',
  125. 'Referrer-Policy' => 'no-referrer',
  126. ],
  127. $headers
  128. );
  129. $this->setupResponse(
  130. 200,
  131. $headers
  132. );
  133. $result = $this->setupcheck->run();
  134. $this->assertEquals(
  135. 'Your server is correctly configured to send security headers.',
  136. $result->getDescription()
  137. );
  138. $this->assertEquals(SetupResult::SUCCESS, $result->getSeverity());
  139. }
  140. public function dataFailure(): array {
  141. return [
  142. // description => modifiedHeaders
  143. 'x-robots-none' => [['X-Robots-Tag' => 'none'], "- The `X-Robots-Tag` HTTP header is not set to `noindex,nofollow`. This is a potential security or privacy risk, as it is recommended to adjust this setting accordingly.\n"],
  144. 'xss-protection-1' => [['X-XSS-Protection' => '1'], "- The `X-XSS-Protection` HTTP header does not contain `1; mode=block`. This is a potential security or privacy risk, as it is recommended to adjust this setting accordingly.\n"],
  145. 'xss-protection-0' => [['X-XSS-Protection' => '0'], "- The `X-XSS-Protection` HTTP header does not contain `1; mode=block`. This is a potential security or privacy risk, as it is recommended to adjust this setting accordingly.\n"],
  146. 'referrer-origin' => [['Referrer-Policy' => 'origin'], "- The `Referrer-Policy` HTTP header is not set to `no-referrer`, `no-referrer-when-downgrade`, `strict-origin`, `strict-origin-when-cross-origin` or `same-origin`. This can leak referer information. See the {w3c-recommendation}.\n"],
  147. 'referrer-origin-when-cross-origin' => [['Referrer-Policy' => 'origin-when-cross-origin'], "- The `Referrer-Policy` HTTP header is not set to `no-referrer`, `no-referrer-when-downgrade`, `strict-origin`, `strict-origin-when-cross-origin` or `same-origin`. This can leak referer information. See the {w3c-recommendation}.\n"],
  148. 'referrer-unsafe-url' => [['Referrer-Policy' => 'unsafe-url'], "- The `Referrer-Policy` HTTP header is not set to `no-referrer`, `no-referrer-when-downgrade`, `strict-origin`, `strict-origin-when-cross-origin` or `same-origin`. This can leak referer information. See the {w3c-recommendation}.\n"],
  149. 'hsts-missing' => [['Strict-Transport-Security' => ''], "- The `Strict-Transport-Security` HTTP header is not set (should be at least `15552000` seconds). For enhanced security, it is recommended to enable HSTS.\n"],
  150. 'hsts-too-low' => [['Strict-Transport-Security' => 'max-age=15551999'], "- The `Strict-Transport-Security` HTTP header is not set to at least `15552000` seconds (current value: `15551999`). For enhanced security, it is recommended to use a long HSTS policy.\n"],
  151. 'hsts-malformed' => [['Strict-Transport-Security' => 'iAmABogusHeader342'], "- The `Strict-Transport-Security` HTTP header is malformed: `iAmABogusHeader342`. For enhanced security, it is recommended to enable HSTS.\n"],
  152. ];
  153. }
  154. /**
  155. * @dataProvider dataFailure
  156. */
  157. public function testFailure(array $headers, string $msg): void {
  158. $headers = array_merge(
  159. [
  160. 'X-XSS-Protection' => '1; mode=block',
  161. 'X-Content-Type-Options' => 'nosniff',
  162. 'X-Robots-Tag' => 'noindex, nofollow',
  163. 'X-Frame-Options' => 'SAMEORIGIN',
  164. 'Strict-Transport-Security' => 'max-age=15768000',
  165. 'X-Permitted-Cross-Domain-Policies' => 'none',
  166. 'Referrer-Policy' => 'no-referrer',
  167. ],
  168. $headers
  169. );
  170. $this->setupResponse(
  171. 200,
  172. $headers
  173. );
  174. $result = $this->setupcheck->run();
  175. $this->assertEquals(
  176. 'Some headers are not set correctly on your instance'."\n$msg",
  177. $result->getDescription()
  178. );
  179. $this->assertEquals(SetupResult::WARNING, $result->getSeverity());
  180. }
  181. protected function setupResponse(int $statuscode, array $headers): void {
  182. $response = $this->createMock(IResponse::class);
  183. $response->expects($this->atLeastOnce())->method('getStatusCode')->willReturn($statuscode);
  184. $response->expects($this->any())->method('getHeader')
  185. ->willReturnCallback(
  186. fn (string $header): string => $headers[$header] ?? ''
  187. );
  188. $this->setupcheck
  189. ->expects($this->atLeastOnce())
  190. ->method('runRequest')
  191. ->willReturnOnConsecutiveCalls($this->generate([$response]));
  192. }
  193. /**
  194. * Helper function creates a nicer interface for mocking Generator behavior
  195. */
  196. protected function generate(array $yield_values) {
  197. return $this->returnCallback(function () use ($yield_values) {
  198. yield from $yield_values;
  199. });
  200. }
  201. }