Passed
Pull Request — 2.4 (#81)
by
unknown
03:20
created
src/Feed/CwpAtomFeed.php 1 patch
Indentation   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -18,57 +18,57 @@
 block discarded – undo
18 18
 
19 19
 class CwpAtomFeed extends RSSFeed
20 20
 {
21
-    public function __construct(
22
-        SS_List $entries,
23
-        $link,
24
-        $title,
25
-        $description = null,
26
-        $titleField = "Title",
27
-        $descriptionField = "Content",
28
-        $authorField = null,
29
-        $lastModified = null,
30
-        $etag = null
31
-    ) {
32
-        parent::__construct(
33
-            $entries,
34
-            $link,
35
-            $title,
36
-            $description,
37
-            $titleField,
38
-            $descriptionField,
39
-            $authorField,
40
-            $lastModified
41
-        );
21
+	public function __construct(
22
+		SS_List $entries,
23
+		$link,
24
+		$title,
25
+		$description = null,
26
+		$titleField = "Title",
27
+		$descriptionField = "Content",
28
+		$authorField = null,
29
+		$lastModified = null,
30
+		$etag = null
31
+	) {
32
+		parent::__construct(
33
+			$entries,
34
+			$link,
35
+			$title,
36
+			$description,
37
+			$titleField,
38
+			$descriptionField,
39
+			$authorField,
40
+			$lastModified
41
+		);
42 42
 
43
-        $this->setTemplate(__CLASS__);
44
-    }
43
+		$this->setTemplate(__CLASS__);
44
+	}
45 45
 
46
-    /**
47
-     * Include an link to the feed
48
-     *
49
-     * @param string $url URL of the feed
50
-     * @param string $title Title to show
51
-     */
52
-    public static function linkToFeed($url, $title = null)
53
-    {
54
-        $title = Convert::raw2xml($title);
55
-        Requirements::insertHeadTags(
56
-            '<link rel="alternate" type="application/atom+xml" title="' . $title .
57
-            '" href="' . $url . '" />'
58
-        );
59
-    }
46
+	/**
47
+	 * Include an link to the feed
48
+	 *
49
+	 * @param string $url URL of the feed
50
+	 * @param string $title Title to show
51
+	 */
52
+	public static function linkToFeed($url, $title = null)
53
+	{
54
+		$title = Convert::raw2xml($title);
55
+		Requirements::insertHeadTags(
56
+			'<link rel="alternate" type="application/atom+xml" title="' . $title .
57
+			'" href="' . $url . '" />'
58
+		);
59
+	}
60 60
 
61
-    /**
62
-     * Output the feed to the browser
63
-     *
64
-     * @return DBHTMLText
65
-     */
66
-    public function outputToBrowser()
67
-    {
68
-        $output = parent::outputToBrowser();
69
-        $response = Controller::curr()->getResponse();
70
-        $response->addHeader("Content-Type", "application/atom+xml");
61
+	/**
62
+	 * Output the feed to the browser
63
+	 *
64
+	 * @return DBHTMLText
65
+	 */
66
+	public function outputToBrowser()
67
+	{
68
+		$output = parent::outputToBrowser();
69
+		$response = Controller::curr()->getResponse();
70
+		$response->addHeader("Content-Type", "application/atom+xml");
71 71
 
72
-        return $output;
73
-    }
72
+		return $output;
73
+	}
74 74
 }
Please login to merge, or discard this patch.
tests/Control/CwpBasicAuthMiddlewareTest.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -97,7 +97,7 @@
 block discarded – undo
97 97
     {
98 98
         $request = new HTTPRequest('GET', $url);
99 99
 
100
-        return $this->middleware->process($request, function () {
100
+        return $this->middleware->process($request, function() {
101 101
             return new HTTPResponse('OK', 200);
102 102
         });
103 103
     }
Please login to merge, or discard this patch.
Indentation   +110 added lines, -110 removed lines patch added patch discarded remove patch
@@ -13,114 +13,114 @@
 block discarded – undo
13 13
 
14 14
 class CwpBasicAuthMiddlewareTest extends SapphireTest
15 15
 {
16
-    /**
17
-     * @var CwpBasicAuthMiddleware
18
-     */
19
-    protected $middleware;
20
-
21
-    /**
22
-     * @var array
23
-     */
24
-    protected $originalServersVars = [];
25
-
26
-    protected function setUp()
27
-    {
28
-        parent::setUp();
29
-
30
-        $this->middleware = Injector::inst()->get(BasicAuthMiddleware::class);
31
-        $this->originalServersVars = $_SERVER;
32
-
33
-        Config::modify()->set(BasicAuth::class, 'ignore_cli', false);
34
-    }
35
-
36
-    protected function tearDown()
37
-    {
38
-        $_SERVER = $this->originalServersVars;
39
-
40
-        parent::tearDown();
41
-    }
42
-
43
-    public function testSetWhitelistedIpsAcceptsStrings()
44
-    {
45
-        $this->middleware->setWhitelistedIps('127.0.0.1,127.0.0.2');
46
-        $this->assertSame([
47
-            '127.0.0.1',
48
-            '127.0.0.2',
49
-        ], $this->middleware->getWhitelistedIps(), 'Accepts comma delimited strings');
50
-    }
51
-
52
-    public function testSetWhitelistedIpsAcceptsArraysOfStrings()
53
-    {
54
-        $this->middleware->setWhitelistedIps(['127.0.0.1']);
55
-        $this->assertSame(['127.0.0.1'], $this->middleware->getWhitelistedIps(), 'Accepts array values');
56
-    }
57
-
58
-    public function testSetWhitelistedIpsSupportedNestedStringListsInsideArrays()
59
-    {
60
-        $this->middleware->setWhitelistedIps([
61
-            '127.0.0.1,127.0.0.2', // Example of `CWP_IP_BYPASS_BASICAUTH` env var value
62
-            ' 137.0.0.1 , 127.0.0.2', // Example of `CWP_IP_BYPASS_BASICAUTH` env var value with added spaces
63
-            '127.0.0.3',
64
-            '127.0.0.3', // check results are unique
65
-            '127.0.0.4',
66
-        ]);
67
-
68
-        $this->assertSame([
69
-            '127.0.0.1',
70
-            '127.0.0.2',
71
-            '137.0.0.1',
72
-            '127.0.0.3',
73
-            '127.0.0.4',
74
-        ], $this->middleware->getWhitelistedIps(), 'Accepts IP list strings inside arrays');
75
-    }
76
-
77
-    /**
78
-     * @param string $currentIp
79
-     * @param int $expected
80
-     * @dataProvider whitelistingProvider
81
-     */
82
-    public function testIpWhitelisting($currentIp, $expected)
83
-    {
84
-        // Enable basic auth everywhere
85
-        $this->middleware->setURLPatterns(['#.*#' => true]);
86
-
87
-        // Set a whitelisted IP address
88
-        $_SERVER['REMOTE_ADDR'] = $currentIp;
89
-        $this->middleware->setWhitelistedIps(['127.0.0.1']);
90
-
91
-        $response = $this->mockRequest();
92
-
93
-        $this->assertEquals($expected, $response->getStatusCode());
94
-    }
95
-
96
-    /**
97
-     * @return array[]
98
-     */
99
-    public function whitelistingProvider()
100
-    {
101
-        return [
102
-            'IP not in whitelist' => ['123.456.789.012', 401],
103
-            'IP in whitelist' => ['127.0.0.1', 200],
104
-        ];
105
-    }
106
-
107
-    public function testMiddlewareProvidesUatServerPermissions()
108
-    {
109
-        $this->assertArrayHasKey('ACCESS_UAT_SERVER', $this->middleware->providePermissions());
110
-    }
111
-
112
-    /**
113
-     * Perform a mock middleware request. Will return 200 if everything is OK.
114
-     *
115
-     * @param string $url
116
-     * @return HTTPResponse
117
-     */
118
-    protected function mockRequest($url = '/foo')
119
-    {
120
-        $request = new HTTPRequest('GET', $url);
121
-
122
-        return $this->middleware->process($request, function () {
123
-            return new HTTPResponse('OK', 200);
124
-        });
125
-    }
16
+	/**
17
+	 * @var CwpBasicAuthMiddleware
18
+	 */
19
+	protected $middleware;
20
+
21
+	/**
22
+	 * @var array
23
+	 */
24
+	protected $originalServersVars = [];
25
+
26
+	protected function setUp()
27
+	{
28
+		parent::setUp();
29
+
30
+		$this->middleware = Injector::inst()->get(BasicAuthMiddleware::class);
31
+		$this->originalServersVars = $_SERVER;
32
+
33
+		Config::modify()->set(BasicAuth::class, 'ignore_cli', false);
34
+	}
35
+
36
+	protected function tearDown()
37
+	{
38
+		$_SERVER = $this->originalServersVars;
39
+
40
+		parent::tearDown();
41
+	}
42
+
43
+	public function testSetWhitelistedIpsAcceptsStrings()
44
+	{
45
+		$this->middleware->setWhitelistedIps('127.0.0.1,127.0.0.2');
46
+		$this->assertSame([
47
+			'127.0.0.1',
48
+			'127.0.0.2',
49
+		], $this->middleware->getWhitelistedIps(), 'Accepts comma delimited strings');
50
+	}
51
+
52
+	public function testSetWhitelistedIpsAcceptsArraysOfStrings()
53
+	{
54
+		$this->middleware->setWhitelistedIps(['127.0.0.1']);
55
+		$this->assertSame(['127.0.0.1'], $this->middleware->getWhitelistedIps(), 'Accepts array values');
56
+	}
57
+
58
+	public function testSetWhitelistedIpsSupportedNestedStringListsInsideArrays()
59
+	{
60
+		$this->middleware->setWhitelistedIps([
61
+			'127.0.0.1,127.0.0.2', // Example of `CWP_IP_BYPASS_BASICAUTH` env var value
62
+			' 137.0.0.1 , 127.0.0.2', // Example of `CWP_IP_BYPASS_BASICAUTH` env var value with added spaces
63
+			'127.0.0.3',
64
+			'127.0.0.3', // check results are unique
65
+			'127.0.0.4',
66
+		]);
67
+
68
+		$this->assertSame([
69
+			'127.0.0.1',
70
+			'127.0.0.2',
71
+			'137.0.0.1',
72
+			'127.0.0.3',
73
+			'127.0.0.4',
74
+		], $this->middleware->getWhitelistedIps(), 'Accepts IP list strings inside arrays');
75
+	}
76
+
77
+	/**
78
+	 * @param string $currentIp
79
+	 * @param int $expected
80
+	 * @dataProvider whitelistingProvider
81
+	 */
82
+	public function testIpWhitelisting($currentIp, $expected)
83
+	{
84
+		// Enable basic auth everywhere
85
+		$this->middleware->setURLPatterns(['#.*#' => true]);
86
+
87
+		// Set a whitelisted IP address
88
+		$_SERVER['REMOTE_ADDR'] = $currentIp;
89
+		$this->middleware->setWhitelistedIps(['127.0.0.1']);
90
+
91
+		$response = $this->mockRequest();
92
+
93
+		$this->assertEquals($expected, $response->getStatusCode());
94
+	}
95
+
96
+	/**
97
+	 * @return array[]
98
+	 */
99
+	public function whitelistingProvider()
100
+	{
101
+		return [
102
+			'IP not in whitelist' => ['123.456.789.012', 401],
103
+			'IP in whitelist' => ['127.0.0.1', 200],
104
+		];
105
+	}
106
+
107
+	public function testMiddlewareProvidesUatServerPermissions()
108
+	{
109
+		$this->assertArrayHasKey('ACCESS_UAT_SERVER', $this->middleware->providePermissions());
110
+	}
111
+
112
+	/**
113
+	 * Perform a mock middleware request. Will return 200 if everything is OK.
114
+	 *
115
+	 * @param string $url
116
+	 * @return HTTPResponse
117
+	 */
118
+	protected function mockRequest($url = '/foo')
119
+	{
120
+		$request = new HTTPRequest('GET', $url);
121
+
122
+		return $this->middleware->process($request, function () {
123
+			return new HTTPResponse('OK', 200);
124
+		});
125
+	}
126 126
 }
Please login to merge, or discard this patch.
tests/PasswordStrengthTest.php 1 patch
Indentation   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -26,30 +26,30 @@
 block discarded – undo
26 26
  */
27 27
 class PasswordStrengthTest extends SapphireTest
28 28
 {
29
-    public function testPasswordMinLength()
30
-    {
31
-        $passwordValidator = Member::password_validator();
32
-        $this->assertGreaterThanOrEqual(10, $passwordValidator->getMinLength());
33
-    }
29
+	public function testPasswordMinLength()
30
+	{
31
+		$passwordValidator = Member::password_validator();
32
+		$this->assertGreaterThanOrEqual(10, $passwordValidator->getMinLength());
33
+	}
34 34
 
35
-    public function testMinTestScore()
36
-    {
37
-        $passwordValidator = Member::password_validator();
38
-        $this->assertGreaterThanOrEqual(3, $passwordValidator->getMinTestScore());
39
-    }
35
+	public function testMinTestScore()
36
+	{
37
+		$passwordValidator = Member::password_validator();
38
+		$this->assertGreaterThanOrEqual(3, $passwordValidator->getMinTestScore());
39
+	}
40 40
 
41
-    public function testHistoricCheckCount()
42
-    {
43
-        $passwordValidator = Member::password_validator();
44
-        $this->assertGreaterThanOrEqual(6, $passwordValidator->getHistoricCount());
45
-    }
41
+	public function testHistoricCheckCount()
42
+	{
43
+		$passwordValidator = Member::password_validator();
44
+		$this->assertGreaterThanOrEqual(6, $passwordValidator->getHistoricCount());
45
+	}
46 46
 
47
-    public function testTestNamesInclude()
48
-    {
49
-        $passwordValidator = Member::password_validator();
50
-        $this->assertContains('lowercase', $passwordValidator->getTestNames());
51
-        $this->assertContains('uppercase', $passwordValidator->getTestNames());
52
-        $this->assertContains('digits', $passwordValidator->getTestNames());
53
-        $this->assertContains('punctuation', $passwordValidator->getTestNames());
54
-    }
47
+	public function testTestNamesInclude()
48
+	{
49
+		$passwordValidator = Member::password_validator();
50
+		$this->assertContains('lowercase', $passwordValidator->getTestNames());
51
+		$this->assertContains('uppercase', $passwordValidator->getTestNames());
52
+		$this->assertContains('digits', $passwordValidator->getTestNames());
53
+		$this->assertContains('punctuation', $passwordValidator->getTestNames());
54
+	}
55 55
 }
Please login to merge, or discard this patch.
tests/Extension/CWPVersionExtensionTest.php 1 patch
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -10,56 +10,56 @@
 block discarded – undo
10 10
 
11 11
 class CWPVersionExtensionTest extends SapphireTest
12 12
 {
13
-    /**
14
-     * @var VersionProvider|PHPUnit_Framework_MockObject_MockObject
15
-     */
16
-    protected $versionProvider;
13
+	/**
14
+	 * @var VersionProvider|PHPUnit_Framework_MockObject_MockObject
15
+	 */
16
+	protected $versionProvider;
17 17
 
18
-    /**
19
-     * @var LeftAndMain|PHPUnit_Framework_MockObject_MockObject
20
-     */
21
-    protected $leftAndMain;
18
+	/**
19
+	 * @var LeftAndMain|PHPUnit_Framework_MockObject_MockObject
20
+	 */
21
+	protected $leftAndMain;
22 22
 
23
-    protected function setUp()
24
-    {
25
-        parent::setUp();
23
+	protected function setUp()
24
+	{
25
+		parent::setUp();
26 26
 
27
-        $this->versionProvider = $this->createMock(VersionProvider::class);
28
-        $this->leftAndMain = $this->createMock(LeftAndMain::class);
27
+		$this->versionProvider = $this->createMock(VersionProvider::class);
28
+		$this->leftAndMain = $this->createMock(LeftAndMain::class);
29 29
 
30
-        $this->leftAndMain
31
-            ->expects($this->atLeastOnce())
32
-            ->method('getVersionProvider')
33
-            ->willReturn($this->versionProvider);
34
-    }
30
+		$this->leftAndMain
31
+			->expects($this->atLeastOnce())
32
+			->method('getVersionProvider')
33
+			->willReturn($this->versionProvider);
34
+	}
35 35
 
36
-    /**
37
-     * @param array $modules
38
-     * @param string $expected
39
-     * @dataProvider getVersionProvider
40
-     */
41
-    public function testGetVersion($modules, $expected)
42
-    {
43
-        $this->versionProvider->expects($this->once())
44
-            ->method('getModuleVersionFromComposer')
45
-            ->willReturn($modules);
36
+	/**
37
+	 * @param array $modules
38
+	 * @param string $expected
39
+	 * @dataProvider getVersionProvider
40
+	 */
41
+	public function testGetVersion($modules, $expected)
42
+	{
43
+		$this->versionProvider->expects($this->once())
44
+			->method('getModuleVersionFromComposer')
45
+			->willReturn($modules);
46 46
 
47
-        $extension = new CWPVersionExtension();
48
-        $extension->setOwner($this->leftAndMain);
47
+		$extension = new CWPVersionExtension();
48
+		$extension->setOwner($this->leftAndMain);
49 49
 
50
-        $result = $extension->getCWPVersionNumber();
51
-        $this->assertSame($expected, $result);
52
-    }
50
+		$result = $extension->getCWPVersionNumber();
51
+		$this->assertSame($expected, $result);
52
+	}
53 53
 
54
-    /**
55
-     * @return array
56
-     */
57
-    public function getVersionProvider()
58
-    {
59
-        return [
60
-            'dev version' => [['cwp/cwp-core' => '2.3.x-dev'], '2.3'],
61
-            'stable version' => [['cwp/cwp-core' => '2.2.0'], '2.2'],
62
-            'not found' => [[], ''],
63
-        ];
64
-    }
54
+	/**
55
+	 * @return array
56
+	 */
57
+	public function getVersionProvider()
58
+	{
59
+		return [
60
+			'dev version' => [['cwp/cwp-core' => '2.3.x-dev'], '2.3'],
61
+			'stable version' => [['cwp/cwp-core' => '2.2.0'], '2.2'],
62
+			'not found' => [[], ''],
63
+		];
64
+	}
65 65
 }
Please login to merge, or discard this patch.
src/Extension/CWPVersionExtension.php 2 patches
Indentation   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -7,23 +7,23 @@
 block discarded – undo
7 7
 
8 8
 class CWPVersionExtension extends Extension
9 9
 {
10
-    /**
11
-     * Gets the version of cwp/cwp-core and returns the major.minor version from it
12
-     *
13
-     * @return string
14
-     */
15
-    public function getCWPVersionNumber()
16
-    {
17
-        /** @var VersionProvider $versionProvider */
18
-        $versionProvider = $this->owner->getVersionProvider();
10
+	/**
11
+	 * Gets the version of cwp/cwp-core and returns the major.minor version from it
12
+	 *
13
+	 * @return string
14
+	 */
15
+	public function getCWPVersionNumber()
16
+	{
17
+		/** @var VersionProvider $versionProvider */
18
+		$versionProvider = $this->owner->getVersionProvider();
19 19
 
20
-        $modules = $versionProvider->getModuleVersionFromComposer(['cwp/cwp-core']);
21
-        if (empty($modules)) {
22
-            return '';
23
-        }
20
+		$modules = $versionProvider->getModuleVersionFromComposer(['cwp/cwp-core']);
21
+		if (empty($modules)) {
22
+			return '';
23
+		}
24 24
 
25
-        // Example: "2.2.x-dev"
26
-        $cwpCore = $modules['cwp/cwp-core'];
27
-        return (string) substr($cwpCore, 0, strpos($cwpCore, '.', 2));
28
-    }
25
+		// Example: "2.2.x-dev"
26
+		$cwpCore = $modules['cwp/cwp-core'];
27
+		return (string) substr($cwpCore, 0, strpos($cwpCore, '.', 2));
28
+	}
29 29
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -24,6 +24,6 @@
 block discarded – undo
24 24
 
25 25
         // Example: "2.2.x-dev"
26 26
         $cwpCore = $modules['cwp/cwp-core'];
27
-        return (string) substr($cwpCore, 0, strpos($cwpCore, '.', 2));
27
+        return (string)substr($cwpCore, 0, strpos($cwpCore, '.', 2));
28 28
     }
29 29
 }
Please login to merge, or discard this patch.
src/Control/InitialisationMiddleware.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@
 block discarded – undo
87 87
          * Environment::getEnv() will fallback to getenv() and will therefore
88 88
          * fetch the variables
89 89
          */
90
-        putenv('http_proxy=' .  $proxy . ':' . $proxyPort);
90
+        putenv('http_proxy=' . $proxy . ':' . $proxyPort);
91 91
         putenv('https_proxy=' . $proxy . ':' . $proxyPort);
92 92
     }
93 93
 
Please login to merge, or discard this patch.
Indentation   +130 added lines, -130 removed lines patch added patch discarded remove patch
@@ -12,143 +12,143 @@
 block discarded – undo
12 12
  */
13 13
 class InitialisationMiddleware implements HTTPMiddleware
14 14
 {
15
-    use Configurable;
16
-
17
-    /**
18
-     * Disable the automatically added 'X-XSS-Protection' header that is added to all responses. This should be left
19
-     * alone in most circumstances to include the header. Refer to Mozilla Developer Network for more information:
20
-     * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection
21
-     *
22
-     * @config
23
-     * @var bool
24
-     */
25
-    private static $xss_protection_enabled = true;
26
-
27
-    /**
28
-     * Enable egress proxy. This works on the principle of setting http(s)_proxy environment variables,
29
-     *  which will be automatically picked up by curl. This means RestfulService and raw curl
30
-     *  requests should work out of the box. Stream-based requests need extra manual configuration.
31
-     *  Refer to https://www.cwp.govt.nz/guides/core-technical-documentation/common-web-platform-core/en/how-tos/external_http_requests_with_proxy
32
-     *
33
-     * @config
34
-     * @var bool
35
-     */
36
-    private static $egress_proxy_default_enabled = true;
37
-
38
-    /**
39
-     * Configure the list of domains to bypass proxy by setting the NO_PROXY environment variable.
40
-     * 'services.cwp.govt.nz' needs to be present for Solr and Docvert internal CWP integration.
41
-     * 'localhost' is necessary for accessing services on the same instance such as tika-server for text extraction.
42
-     *
43
-     * @config
44
-     * @var string[]
45
-     */
46
-    private static $egress_proxy_exclude_domains = [
47
-        'services.cwp.govt.nz',
48
-        'localhost',
49
-    ];
50
-
51
-    /**
52
-     * Provide a value for the HTTP Strict Transport Security header.
53
-     * This header is only respected if you also redirect to SSL.
54
-     *
55
-     * Example configuration (short max-age, excluding dev environments):
56
-     * ```yml
57
-     * ---
58
-     * Name: appsecurity
59
-     * After: '#cwpsecurity'
60
-     * Except:
61
-     *   environment: dev
62
-     * ---
63
-     * CWP\Core\Control\InitialisationMiddleware:
64
-     *   strict_transport_security: 'max-age=300'
65
-     * SilverStripe\Core\Injector\Injector:
66
-     *   SilverStripe\Control\Middleware\CanonicalURLMiddleware:
67
-     *     properties:
68
-     *       ForceSSL: true
69
-     *       ForceSSLPatterns: null
70
-     * ```
71
-     *
72
-     * Note: This is enabled by default in `cwp/installer` starting with 2.4.x,
73
-     * see `app/_config/security.yml`.
74
-     *
75
-     * @see https://www.cwp.govt.nz/developer-docs/en/2/working_with_projects/security/
76
-     * @config
77
-     * @var string
78
-     */
79
-    private static $strict_transport_security = null;
80
-
81
-    public function process(HTTPRequest $request, callable $delegate)
82
-    {
83
-        if ($this->config()->get('egress_proxy_default_enabled')) {
84
-            $this->configureEgressProxy();
85
-        }
86
-
87
-        $this->configureProxyDomainExclusions();
88
-
89
-        $response = $delegate($request);
90
-
91
-        if ($this->config()->get('xss_protection_enabled') && $response) {
92
-            $response->addHeader('X-XSS-Protection', '1; mode=block');
93
-        }
94
-
95
-        $hsts = $this->config()->get('strict_transport_security');
96
-        if ($hsts && $response) {
97
-            $response->addHeader('Strict-Transport-Security', $hsts);
98
-        }
99
-
100
-        return $response;
101
-    }
102
-
103
-    /**
104
-     * If the outbound egress proxy details have been defined in environment variables, configure the proxy
105
-     * variables that are used to configure it.
106
-     */
107
-    protected function configureEgressProxy()
108
-    {
109
-        if (!Environment::getEnv('SS_OUTBOUND_PROXY')
110
-            || !Environment::getEnv('SS_OUTBOUND_PROXY_PORT')
111
-        ) {
112
-            return;
113
-        }
114
-
115
-        $proxy = Environment::getEnv('SS_OUTBOUND_PROXY');
116
-        $proxyPort = Environment::getEnv('SS_OUTBOUND_PROXY_PORT');
117
-
118
-        /*
15
+	use Configurable;
16
+
17
+	/**
18
+	 * Disable the automatically added 'X-XSS-Protection' header that is added to all responses. This should be left
19
+	 * alone in most circumstances to include the header. Refer to Mozilla Developer Network for more information:
20
+	 * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection
21
+	 *
22
+	 * @config
23
+	 * @var bool
24
+	 */
25
+	private static $xss_protection_enabled = true;
26
+
27
+	/**
28
+	 * Enable egress proxy. This works on the principle of setting http(s)_proxy environment variables,
29
+	 *  which will be automatically picked up by curl. This means RestfulService and raw curl
30
+	 *  requests should work out of the box. Stream-based requests need extra manual configuration.
31
+	 *  Refer to https://www.cwp.govt.nz/guides/core-technical-documentation/common-web-platform-core/en/how-tos/external_http_requests_with_proxy
32
+	 *
33
+	 * @config
34
+	 * @var bool
35
+	 */
36
+	private static $egress_proxy_default_enabled = true;
37
+
38
+	/**
39
+	 * Configure the list of domains to bypass proxy by setting the NO_PROXY environment variable.
40
+	 * 'services.cwp.govt.nz' needs to be present for Solr and Docvert internal CWP integration.
41
+	 * 'localhost' is necessary for accessing services on the same instance such as tika-server for text extraction.
42
+	 *
43
+	 * @config
44
+	 * @var string[]
45
+	 */
46
+	private static $egress_proxy_exclude_domains = [
47
+		'services.cwp.govt.nz',
48
+		'localhost',
49
+	];
50
+
51
+	/**
52
+	 * Provide a value for the HTTP Strict Transport Security header.
53
+	 * This header is only respected if you also redirect to SSL.
54
+	 *
55
+	 * Example configuration (short max-age, excluding dev environments):
56
+	 * ```yml
57
+	 * ---
58
+	 * Name: appsecurity
59
+	 * After: '#cwpsecurity'
60
+	 * Except:
61
+	 *   environment: dev
62
+	 * ---
63
+	 * CWP\Core\Control\InitialisationMiddleware:
64
+	 *   strict_transport_security: 'max-age=300'
65
+	 * SilverStripe\Core\Injector\Injector:
66
+	 *   SilverStripe\Control\Middleware\CanonicalURLMiddleware:
67
+	 *     properties:
68
+	 *       ForceSSL: true
69
+	 *       ForceSSLPatterns: null
70
+	 * ```
71
+	 *
72
+	 * Note: This is enabled by default in `cwp/installer` starting with 2.4.x,
73
+	 * see `app/_config/security.yml`.
74
+	 *
75
+	 * @see https://www.cwp.govt.nz/developer-docs/en/2/working_with_projects/security/
76
+	 * @config
77
+	 * @var string
78
+	 */
79
+	private static $strict_transport_security = null;
80
+
81
+	public function process(HTTPRequest $request, callable $delegate)
82
+	{
83
+		if ($this->config()->get('egress_proxy_default_enabled')) {
84
+			$this->configureEgressProxy();
85
+		}
86
+
87
+		$this->configureProxyDomainExclusions();
88
+
89
+		$response = $delegate($request);
90
+
91
+		if ($this->config()->get('xss_protection_enabled') && $response) {
92
+			$response->addHeader('X-XSS-Protection', '1; mode=block');
93
+		}
94
+
95
+		$hsts = $this->config()->get('strict_transport_security');
96
+		if ($hsts && $response) {
97
+			$response->addHeader('Strict-Transport-Security', $hsts);
98
+		}
99
+
100
+		return $response;
101
+	}
102
+
103
+	/**
104
+	 * If the outbound egress proxy details have been defined in environment variables, configure the proxy
105
+	 * variables that are used to configure it.
106
+	 */
107
+	protected function configureEgressProxy()
108
+	{
109
+		if (!Environment::getEnv('SS_OUTBOUND_PROXY')
110
+			|| !Environment::getEnv('SS_OUTBOUND_PROXY_PORT')
111
+		) {
112
+			return;
113
+		}
114
+
115
+		$proxy = Environment::getEnv('SS_OUTBOUND_PROXY');
116
+		$proxyPort = Environment::getEnv('SS_OUTBOUND_PROXY_PORT');
117
+
118
+		/*
119 119
          * This sets the environment variables so they are available in
120 120
          * external calls executed by exec() such as curl.
121 121
          * Environment::setEnv() would only availabe in context of SilverStripe.
122 122
          * Environment::getEnv() will fallback to getenv() and will therefore
123 123
          * fetch the variables
124 124
          */
125
-        putenv('http_proxy=' .  $proxy . ':' . $proxyPort);
126
-        putenv('https_proxy=' . $proxy . ':' . $proxyPort);
127
-    }
128
-
129
-    /**
130
-     * Configure any domains that should be excluded from egress proxy rules and provide them to the environment
131
-     */
132
-    protected function configureProxyDomainExclusions()
133
-    {
134
-        $noProxy = $this->config()->get('egress_proxy_exclude_domains');
135
-        if (empty($noProxy)) {
136
-            return;
137
-        }
138
-
139
-        if (!is_array($noProxy)) {
140
-            $noProxy = [$noProxy];
141
-        }
142
-
143
-        // Merge with exsiting if needed.
144
-        if (Environment::getEnv('NO_PROXY')) {
145
-            $noProxy = array_merge(explode(',', Environment::getEnv('NO_PROXY')), $noProxy);
146
-        }
147
-
148
-        /*
125
+		putenv('http_proxy=' .  $proxy . ':' . $proxyPort);
126
+		putenv('https_proxy=' . $proxy . ':' . $proxyPort);
127
+	}
128
+
129
+	/**
130
+	 * Configure any domains that should be excluded from egress proxy rules and provide them to the environment
131
+	 */
132
+	protected function configureProxyDomainExclusions()
133
+	{
134
+		$noProxy = $this->config()->get('egress_proxy_exclude_domains');
135
+		if (empty($noProxy)) {
136
+			return;
137
+		}
138
+
139
+		if (!is_array($noProxy)) {
140
+			$noProxy = [$noProxy];
141
+		}
142
+
143
+		// Merge with exsiting if needed.
144
+		if (Environment::getEnv('NO_PROXY')) {
145
+			$noProxy = array_merge(explode(',', Environment::getEnv('NO_PROXY')), $noProxy);
146
+		}
147
+
148
+		/*
149 149
          * Set the environment varial for NO_PROXY the same way the
150 150
          * proxy variables are set above
151 151
          */
152
-        putenv('NO_PROXY=' . implode(',', array_unique($noProxy)));
153
-    }
152
+		putenv('NO_PROXY=' . implode(',', array_unique($noProxy)));
153
+	}
154 154
 }
Please login to merge, or discard this patch.
src/Control/CwpBasicAuthMiddleware.php 1 patch
Indentation   +85 added lines, -85 removed lines patch added patch discarded remove patch
@@ -8,98 +8,98 @@
 block discarded – undo
8 8
 
9 9
 class CwpBasicAuthMiddleware extends BasicAuthMiddleware implements PermissionProvider
10 10
 {
11
-    /**
12
-     * Whitelisted IP addresses will not be given a basic authentication prompt when other basic authentication
13
-     * rules via {@link BasicAuthMiddleware} are enabled.
14
-     *
15
-     * Please note that this will not have any effect if using BasicAuth.entire_site_protected, which will
16
-     * always enabled basic authentication for the entire site.
17
-     *
18
-     * @var array
19
-     */
20
-    protected $whitelistedIps = [];
11
+	/**
12
+	 * Whitelisted IP addresses will not be given a basic authentication prompt when other basic authentication
13
+	 * rules via {@link BasicAuthMiddleware} are enabled.
14
+	 *
15
+	 * Please note that this will not have any effect if using BasicAuth.entire_site_protected, which will
16
+	 * always enabled basic authentication for the entire site.
17
+	 *
18
+	 * @var array
19
+	 */
20
+	protected $whitelistedIps = [];
21 21
 
22
-    /**
23
-     * @return array
24
-     */
25
-    public function getWhitelistedIps()
26
-    {
27
-        return $this->whitelistedIps;
28
-    }
22
+	/**
23
+	 * @return array
24
+	 */
25
+	public function getWhitelistedIps()
26
+	{
27
+		return $this->whitelistedIps;
28
+	}
29 29
 
30
-    /**
31
-     * @param string|string[] $whitelistedIps An array of IP addresses, a comma delimited string, or an array of IPs
32
-     *                                        or comma delimited IP list strings
33
-     * @return $this
34
-     */
35
-    public function setWhitelistedIps($whitelistedIps)
36
-    {
37
-        // Allow string or array input
38
-        $ipLists = is_array($whitelistedIps) ? $whitelistedIps : [$whitelistedIps];
30
+	/**
31
+	 * @param string|string[] $whitelistedIps An array of IP addresses, a comma delimited string, or an array of IPs
32
+	 *                                        or comma delimited IP list strings
33
+	 * @return $this
34
+	 */
35
+	public function setWhitelistedIps($whitelistedIps)
36
+	{
37
+		// Allow string or array input
38
+		$ipLists = is_array($whitelistedIps) ? $whitelistedIps : [$whitelistedIps];
39 39
 
40
-        $whitelistedIps = [];
41
-        // Break each string in the array by commas to support nested IP lists
42
-        foreach ($ipLists as $ipList) {
43
-            if (!$ipList) {
44
-                continue;
45
-            }
46
-            $ips = array_map('trim', explode(',', $ipList));
47
-            $whitelistedIps = array_merge($whitelistedIps, $ips);
48
-        }
40
+		$whitelistedIps = [];
41
+		// Break each string in the array by commas to support nested IP lists
42
+		foreach ($ipLists as $ipList) {
43
+			if (!$ipList) {
44
+				continue;
45
+			}
46
+			$ips = array_map('trim', explode(',', $ipList));
47
+			$whitelistedIps = array_merge($whitelistedIps, $ips);
48
+		}
49 49
 
50
-        // Return unique values with keys reset
51
-        $this->whitelistedIps = array_values(array_unique($whitelistedIps));
52
-        return $this;
53
-    }
50
+		// Return unique values with keys reset
51
+		$this->whitelistedIps = array_values(array_unique($whitelistedIps));
52
+		return $this;
53
+	}
54 54
 
55
-    /**
56
-     * Check for any whitelisted IP addresses. If one matches the current user's IP then return false early,
57
-     * otherwise allow the default {@link BasicAuthMiddleware} to continue its logic.
58
-     *
59
-     * {@inheritDoc}
60
-     */
61
-    protected function checkMatchingURL(HTTPRequest $request)
62
-    {
63
-        if ($this->ipMatchesWhitelist()) {
64
-            return false;
65
-        }
66
-        return parent::checkMatchingURL($request);
67
-    }
55
+	/**
56
+	 * Check for any whitelisted IP addresses. If one matches the current user's IP then return false early,
57
+	 * otherwise allow the default {@link BasicAuthMiddleware} to continue its logic.
58
+	 *
59
+	 * {@inheritDoc}
60
+	 */
61
+	protected function checkMatchingURL(HTTPRequest $request)
62
+	{
63
+		if ($this->ipMatchesWhitelist()) {
64
+			return false;
65
+		}
66
+		return parent::checkMatchingURL($request);
67
+	}
68 68
 
69
-    /**
70
-     * Check whether the current user's IP address is in the IP whitelist
71
-     *
72
-     * @return bool
73
-     */
74
-    protected function ipMatchesWhitelist()
75
-    {
76
-        $whitelist = $this->getWhitelistedIps();
77
-        // Continue if no whitelist is defined
78
-        if (empty($whitelist)) {
79
-            return false;
80
-        }
69
+	/**
70
+	 * Check whether the current user's IP address is in the IP whitelist
71
+	 *
72
+	 * @return bool
73
+	 */
74
+	protected function ipMatchesWhitelist()
75
+	{
76
+		$whitelist = $this->getWhitelistedIps();
77
+		// Continue if no whitelist is defined
78
+		if (empty($whitelist)) {
79
+			return false;
80
+		}
81 81
 
82
-        $userIp = $_SERVER['REMOTE_ADDR'];
83
-        if (in_array($userIp, $whitelist)) {
84
-            return true;
85
-        }
82
+		$userIp = $_SERVER['REMOTE_ADDR'];
83
+		if (in_array($userIp, $whitelist)) {
84
+			return true;
85
+		}
86 86
 
87
-        return false;
88
-    }
87
+		return false;
88
+	}
89 89
 
90
-    /**
91
-     * Provide a permission code for users to be able to access the site in test mode (UAT sites). This will
92
-     * apply to any route other than those required to change your password.
93
-     *
94
-     * @return array
95
-     */
96
-    public function providePermissions()
97
-    {
98
-        return [
99
-            'ACCESS_UAT_SERVER' => _t(
100
-                __CLASS__ . '.UatServerPermission',
101
-                'Allow users to use their accounts to access the UAT server'
102
-            )
103
-        ];
104
-    }
90
+	/**
91
+	 * Provide a permission code for users to be able to access the site in test mode (UAT sites). This will
92
+	 * apply to any route other than those required to change your password.
93
+	 *
94
+	 * @return array
95
+	 */
96
+	public function providePermissions()
97
+	{
98
+		return [
99
+			'ACCESS_UAT_SERVER' => _t(
100
+				__CLASS__ . '.UatServerPermission',
101
+				'Allow users to use their accounts to access the UAT server'
102
+			)
103
+		];
104
+	}
105 105
 }
Please login to merge, or discard this patch.
src/PasswordEncryptor/PBKDF2.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -29,7 +29,7 @@  discard block
 block discarded – undo
29 29
     {
30 30
         parent::__construct($algorithm);
31 31
 
32
-        if ($iterations !== null) {
32
+        if ($iterations!==null) {
33 33
             $this->iterations = $iterations;
34 34
         }
35 35
     }
@@ -44,6 +44,6 @@  discard block
 block discarded – undo
44 44
 
45 45
     public function encrypt($password, $salt = null, $member = null)
46 46
     {
47
-        return hash_pbkdf2($this->getAlgorithm(), (string) $password, (string) $salt, $this->getIterations());
47
+        return hash_pbkdf2($this->getAlgorithm(), (string)$password, (string)$salt, $this->getIterations());
48 48
     }
49 49
 }
Please login to merge, or discard this patch.
Indentation   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -11,39 +11,39 @@
 block discarded – undo
11 11
  */
12 12
 class PBKDF2 extends PasswordEncryptor_PHPHash
13 13
 {
14
-    /**
15
-     * The number of internal iterations for hash_pbkdf2() to perform for the derivation. Please note that if you
16
-     * change this from the default value you will break existing hashes stored in the database, so these would
17
-     * need to be regenerated.
18
-     *
19
-     * @var int
20
-     */
21
-    protected $iterations = 30000;
14
+	/**
15
+	 * The number of internal iterations for hash_pbkdf2() to perform for the derivation. Please note that if you
16
+	 * change this from the default value you will break existing hashes stored in the database, so these would
17
+	 * need to be regenerated.
18
+	 *
19
+	 * @var int
20
+	 */
21
+	protected $iterations = 30000;
22 22
 
23
-    /**
24
-     * @param string $algorithm
25
-     * @param int|null $iterations
26
-     * @throws Exception If the provided algorithm is not available in the current environment
27
-     */
28
-    public function __construct(string $algorithm, int $iterations = null)
29
-    {
30
-        parent::__construct($algorithm);
23
+	/**
24
+	 * @param string $algorithm
25
+	 * @param int|null $iterations
26
+	 * @throws Exception If the provided algorithm is not available in the current environment
27
+	 */
28
+	public function __construct(string $algorithm, int $iterations = null)
29
+	{
30
+		parent::__construct($algorithm);
31 31
 
32
-        if ($iterations !== null) {
33
-            $this->iterations = $iterations;
34
-        }
35
-    }
32
+		if ($iterations !== null) {
33
+			$this->iterations = $iterations;
34
+		}
35
+	}
36 36
 
37
-    /**
38
-     * @return int
39
-     */
40
-    public function getIterations(): int
41
-    {
42
-        return $this->iterations;
43
-    }
37
+	/**
38
+	 * @return int
39
+	 */
40
+	public function getIterations(): int
41
+	{
42
+		return $this->iterations;
43
+	}
44 44
 
45
-    public function encrypt($password, $salt = null, $member = null)
46
-    {
47
-        return hash_pbkdf2($this->getAlgorithm(), (string) $password, (string) $salt, $this->getIterations());
48
-    }
45
+	public function encrypt($password, $salt = null, $member = null)
46
+	{
47
+		return hash_pbkdf2($this->getAlgorithm(), (string) $password, (string) $salt, $this->getIterations());
48
+	}
49 49
 }
Please login to merge, or discard this patch.
tests/PasswordEncryptor/PBKDF2Test.php 1 patch
Indentation   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -8,30 +8,30 @@
 block discarded – undo
8 8
 
9 9
 class PBKDF2Test extends SapphireTest
10 10
 {
11
-    public function testGetIterations()
12
-    {
13
-        $encryptor = new PBKDF2('sha512', 12345);
14
-        $this->assertSame(12345, $encryptor->getIterations());
15
-    }
11
+	public function testGetIterations()
12
+	{
13
+		$encryptor = new PBKDF2('sha512', 12345);
14
+		$this->assertSame(12345, $encryptor->getIterations());
15
+	}
16 16
 
17
-    public function testEncrypt()
18
-    {
19
-        $encryptor = new PBKDF2('sha512', 10000);
20
-        $salt = 'predictablesaltforunittesting';
21
-        $result = $encryptor->encrypt('opensesame', $salt);
22
-        $this->assertSame(
23
-            '6bafcacb90',
24
-            substr($result, 0, 10),
25
-            'Hashed password with predictable salt did not match fixtured expectation'
26
-        );
27
-    }
17
+	public function testEncrypt()
18
+	{
19
+		$encryptor = new PBKDF2('sha512', 10000);
20
+		$salt = 'predictablesaltforunittesting';
21
+		$result = $encryptor->encrypt('opensesame', $salt);
22
+		$this->assertSame(
23
+			'6bafcacb90',
24
+			substr($result, 0, 10),
25
+			'Hashed password with predictable salt did not match fixtured expectation'
26
+		);
27
+	}
28 28
 
29
-    /**
30
-     * @expectedException Exception
31
-     * @expectedExceptionMessage Hash algorithm "foobar" not found
32
-     */
33
-    public function testThrowsExceptionWhenInvalidAlgorithmIsProvided()
34
-    {
35
-        new PBKDF2('foobar');
36
-    }
29
+	/**
30
+	 * @expectedException Exception
31
+	 * @expectedExceptionMessage Hash algorithm "foobar" not found
32
+	 */
33
+	public function testThrowsExceptionWhenInvalidAlgorithmIsProvided()
34
+	{
35
+		new PBKDF2('foobar');
36
+	}
37 37
 }
Please login to merge, or discard this patch.