• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nette / http / 33039526928

27 Aug 2026 04:23AM UTC coverage: 83.509% (+0.4%) from 83.115%
33039526928

push

github

dg
uses #Deprecated wip

1109 of 1328 relevant lines covered (83.51%)

0.84 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

72.63
/src/Bridges/HttpDI/HttpExtension.php
1
<?php declare(strict_types=1);
2

3
/**
4
 * This file is part of the Nette Framework (https://nette.org)
5
 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6
 */
7

8
namespace Nette\Bridges\HttpDI;
9

10
use Nette;
11
use Nette\Schema\Expect;
12
use function is_array, strval;
13

14

15
/**
16
 * HTTP extension for Nette DI.
17
 *
18
 * @property object{
19
 *     proxy: array<string>,
20
 *     proxyHeaders: string,
21
 *     forceHttps: bool,
22
 *     baseUrl: ?string,
23
 *     headers: array<string, ?scalar>,
24
 *     frames: string|bool|null,
25
 *     csp: array<string, array<mixed>|scalar|null>,
26
 *     cspReportOnly: array<string, array<mixed>|scalar|null>,
27
 *     featurePolicy: array<string, array<mixed>|scalar|null>,
28
 *     cookiePath: ?string,
29
 *     cookieDomain: ?string,
30
 *     cookieSecure: bool|'auto'|null,
31
 *     disableNetteCookie: bool,
32
 * } $config
33
 */
34
class HttpExtension extends Nette\DI\CompilerExtension
35
{
36
        public function __construct(
1✔
37
                private readonly bool $cliMode = false,
38
        ) {
39
        }
1✔
40

41

42
        public function getConfigSchema(): Nette\Schema\Schema
43
        {
44
                return Expect::structure([
1✔
45
                        'proxy' => Expect::anyOf(Expect::arrayOf('string'), Expect::string()->castTo('array'))->firstIsDefault()->dynamic(),
1✔
46
                        'proxyHeaders' => Expect::anyOf('xForwarded', 'forwarded', 'both', 'none')->firstIsDefault(),
1✔
47
                        'forceHttps' => Expect::bool(false)->dynamic(),
1✔
48
                        'baseUrl' => Expect::string()->dynamic(),
1✔
49
                        'headers' => Expect::arrayOf('scalar|null')->default([
1✔
50
                                'X-Powered-By' => 'Nette Framework 3',
1✔
51
                                'Content-Type' => 'text/html; charset=utf-8',
52
                        ])->mergeDefaults(),
1✔
53
                        'frames' => Expect::anyOf(Expect::string(), Expect::bool(), null)->default('SAMEORIGIN'), // X-Frame-Options
1✔
54
                        'csp' => Expect::arrayOf('array|scalar|null'), // Content-Security-Policy
1✔
55
                        'cspReportOnly' => Expect::arrayOf('array|scalar|null'), // Content-Security-Policy-Report-Only
1✔
56
                        'featurePolicy' => Expect::arrayOf('array|scalar|null'), // Feature-Policy
1✔
57
                        'cookiePath' => Expect::string()->dynamic(),
1✔
58
                        'cookieDomain' => Expect::string()->dynamic(),
1✔
59
                        'cookieSecure' => Expect::anyOf('auto', null, true, false)->firstIsDefault()->dynamic(), // Whether the cookie is available only through HTTPS
1✔
60
                        'disableNetteCookie' => Expect::bool(false)->deprecated(),
1✔
61
                ]);
62
        }
63

64

65
        public function loadConfiguration(): void
66
        {
67
                $builder = $this->getContainerBuilder();
1✔
68
                $config = $this->config;
1✔
69

70
                $requestFactory = $builder->addDefinition($this->prefix('requestFactory'))
1✔
71
                        ->setFactory(Nette\Http\RequestFactory::class)
1✔
72
                        ->addSetup('setProxy', [
1✔
73
                                $config->proxy,
1✔
74
                                'forwarded' => $config->proxyHeaders === 'forwarded' || $config->proxyHeaders === 'both',
1✔
75
                                'xForwarded' => $config->proxyHeaders === 'xForwarded' || $config->proxyHeaders === 'both',
1✔
76
                        ]);
77

78
                if ($config->forceHttps) {
1✔
79
                        $requestFactory->addSetup('setForceHttps');
×
80
                }
81

82
                if ($config->baseUrl !== null) {
1✔
83
                        $requestFactory->addSetup('setBaseUrl', [$config->baseUrl]);
1✔
84
                }
85

86
                $request = $builder->addDefinition($this->prefix('request'))
1✔
87
                        ->setFactory('@Nette\Http\RequestFactory::fromGlobals');
1✔
88

89
                $response = $builder->addDefinition($this->prefix('response'))
1✔
90
                        ->setFactory(Nette\Http\Response::class);
1✔
91

92
                if ($config->cookiePath !== null) {
1✔
93
                        $response->addSetup('$cookiePath', [$config->cookiePath]);
1✔
94
                }
95

96
                if ($config->cookieDomain !== null) {
1✔
97
                        $value = $config->cookieDomain === 'domain'
1✔
98
                                ? $builder::literal('$this->getService(?)->getUrl()->getDomain(2)', [$request->getName()])
1✔
99
                                : $config->cookieDomain;
1✔
100
                        $response->addSetup('$cookieDomain', [$value]);
1✔
101
                }
102

103
                if ($config->cookieSecure !== null) {
1✔
104
                        $value = $config->cookieSecure === 'auto'
1✔
105
                                ? $builder::literal('$this->getService(?)->isSecured()', [$request->getName()])
1✔
106
                                : $config->cookieSecure;
1✔
107
                        $response->addSetup('$cookieSecure', [$value]);
1✔
108
                }
109

110
                if ($this->name === 'http') {
1✔
111
                        $builder->addAlias('nette.httpRequestFactory', $this->prefix('requestFactory'));
1✔
112
                        $builder->addAlias('httpRequest', $this->prefix('request'));
1✔
113
                        $builder->addAlias('httpResponse', $this->prefix('response'));
1✔
114
                }
115

116
                if (!$this->cliMode) {
1✔
117
                        $this->sendHeaders();
1✔
118
                }
119
        }
1✔
120

121

122
        private function sendHeaders(): void
123
        {
124
                $config = $this->config;
1✔
125
                $headers = array_map(strval(...), $config->headers);
1✔
126

127
                if (isset($config->frames) && $config->frames !== true && !isset($headers['X-Frame-Options'])) {
1✔
128
                        $frames = $config->frames;
1✔
129
                        if ($frames === false) {
1✔
130
                                $frames = 'DENY';
×
131
                        } elseif (preg_match('#^https?:#', $frames)) {
1✔
132
                                $frames = "ALLOW-FROM $frames";
×
133
                        }
134

135
                        $headers['X-Frame-Options'] = $frames;
1✔
136
                }
137

138
                foreach (['csp', 'cspReportOnly'] as $key) {
1✔
139
                        if (empty($config->$key)) {
1✔
140
                                continue;
1✔
141
                        }
142

143
                        $value = self::buildPolicy($config->$key);
×
144
                        if (str_contains($value, "'nonce'")) {
×
145
                                $this->initialization->addBody('$cspNonce = base64_encode(random_bytes(16));');
×
146
                                $value = Nette\DI\ContainerBuilder::literal(
×
147
                                        'str_replace(?, ? . $cspNonce, ?)',
×
148
                                        ["'nonce", "'nonce-", $value],
×
149
                                );
150
                        }
151

152
                        $headers['Content-Security-Policy' . ($key === 'csp' ? '' : '-Report-Only')] = $value;
×
153
                }
154

155
                if (!empty($config->featurePolicy)) {
1✔
156
                        $headers['Feature-Policy'] = self::buildPolicy($config->featurePolicy);
×
157
                }
158

159
                $this->initialization->addBody('$response = $this->getService(?);', [$this->prefix('response')]);
1✔
160
                foreach ($headers as $key => $value) {
1✔
161
                        if ($value !== '') {
1✔
162
                                $this->initialization->addBody('$response->setHeader(?, ?);', [$key, $value]);
1✔
163
                        }
164
                }
165
        }
1✔
166

167

168
        /** @param array<string, array<mixed>|scalar|null>  $config */
169
        private static function buildPolicy(array $config): string
170
        {
171
                $nonQuoted = ['require-sri-for' => 1, 'sandbox' => 1];
×
172
                $value = '';
×
173
                foreach ($config as $type => $policy) {
×
174
                        if ($policy === false) {
×
175
                                continue;
×
176
                        }
177

178
                        $policy = $policy === true ? [] : (array) $policy;
×
179
                        $value .= $type;
×
180
                        foreach ($policy as $item) {
×
181
                                if (is_array($item)) {
×
182
                                        $item = key($item) . ':';
×
183
                                }
184

185
                                $value .= !isset($nonQuoted[$type]) && preg_match('#^[a-z-]+$#D', $item)
×
186
                                        ? " '$item'"
×
187
                                        : " $item";
×
188
                        }
189

190
                        $value .= '; ';
×
191
                }
192

193
                return $value;
×
194
        }
195
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc