Passed
Pull Request — master (#236)
by
unknown
13:02
created

ForceSecureConnection::addCSP()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 5
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Web\Middleware;
6
7
use Psr\Http\Message\ResponseFactoryInterface;
8
use Psr\Http\Message\ResponseInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Psr\Http\Server\MiddlewareInterface;
11
use Psr\Http\Server\RequestHandlerInterface;
12
use Yiisoft\Http\Status;
13
14
/**
15
 * Redirects from HTTP to HTTPS and adds CSP and HSTS headers
16
 */
17
class ForceSecureConnection implements MiddlewareInterface
18
{
19
    protected int $statusCode = Status::MOVED_PERMANENTLY;
20
    protected ?int $port = null;
21
22
    protected bool $addCSP = true;
23
    protected string $cspDirective = 'upgrade-insecure-requests';
24
25
    protected bool $addSTS = true;
26
    protected int $stsMaxAge = 31_536_000; // 12 months
0 ignored issues
show
Bug introduced by
The constant Yiisoft\Yii\Web\Middleware\31_536_000 was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
27
    protected bool $stsSubDomains = false;
28
29
    private ResponseFactoryInterface $responseFactory;
30
31
    public function __construct(ResponseFactoryInterface $responseFactory) {
32
        $this->responseFactory = $responseFactory;
33
    }
34
35
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
36
    {
37
        if ($request->getUri()->getScheme() === 'http') {
38
            $url = (string)$request->getUri()->withScheme('https')->withPort($this->port);
39
            return $this->addCSP(
40
                $this->responseFactory
41
                    ->createResponse($this->statusCode)
42
                    ->withHeader('Location', $url)
43
            );
44
        }
45
        return $this->addSTS($this->addCSP($handler->handle($request)));
46
    }
47
48
    /**
49
     * Add Content-Security-Policy header
50
     */
51
    private function addCSP(ResponseInterface $response): ResponseInterface
52
    {
53
        return $this->addCSP
54
            ? $response->withHeader('Content-Security-Policy', $this->cspDirective)
55
            : $response;
56
    }
57
58
    /**
59
     * Add Strict-Transport-Security header
60
     */
61
    private function addSTS(ResponseInterface $response): ResponseInterface
62
    {
63
        $subDomains = $this->stsSubDomains ? 'includeSubDomains' : '';
64
        return $this->addSTS
65
            ? $response->withHeader('Strict-Transport-Security', "max-age={$this->stsMaxAge}; {$subDomains}")
66
            : $response;
67
    }
68
}
69