/
UserContextListener.php
233 lines (202 loc) · 8.75 KB
/
UserContextListener.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
<?php
/*
* This file is part of the FOSHttpCacheBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FOS\HttpCacheBundle\EventListener;
use FOS\HttpCache\ResponseTagger;
use FOS\HttpCache\UserContext\HashGenerator;
use FOS\HttpCacheBundle\UserContextInvalidator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\EventListener\AbstractSessionListener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Check requests and responses with the matcher.
*
* Abort context hash requests immediately and return the hash.
* Add the vary information on responses to normal requests.
*
* @author Stefan Paschke <stefan.paschke@gmail.com>
* @author Joel Wurtz <joel.wurtz@gmail.com>
*/
class UserContextListener implements EventSubscriberInterface
{
private RequestMatcherInterface $requestMatcher;
private HashGenerator $hashGenerator;
/**
* If the response tagger is set, the hash lookup response is tagged with the session id for later invalidation.
*/
private ?ResponseTagger $responseTagger;
private array $options;
/**
* Whether the application has a session listener and therefore could
* require the AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER.
*/
private bool $hasSessionListener;
private bool $wasAnonymous = false;
/**
* Used to exclude anonymous requests (no authentication nor session) from user hash sanity check.
* It prevents issues when the hash generator that is used returns a customized value for anonymous users,
* that differs from the documented, hardcoded one.
*/
private ?RequestMatcherInterface $anonymousRequestMatcher;
public function __construct(
RequestMatcherInterface $requestMatcher,
HashGenerator $hashGenerator,
RequestMatcherInterface $anonymousRequestMatcher = null,
ResponseTagger $responseTagger = null,
array $options = [],
bool $hasSessionListener = true
) {
$this->requestMatcher = $requestMatcher;
$this->hashGenerator = $hashGenerator;
$this->anonymousRequestMatcher = $anonymousRequestMatcher;
$this->responseTagger = $responseTagger;
$this->hasSessionListener = $hasSessionListener;
$resolver = new OptionsResolver();
$resolver->setDefaults([
'user_identifier_headers' => ['Cookie', 'Authorization'],
'user_hash_header' => 'X-User-Context-Hash',
'ttl' => 0,
'add_vary_on_hash' => true,
]);
$resolver->setRequired(['user_identifier_headers', 'user_hash_header']);
$resolver->setAllowedTypes('user_identifier_headers', 'array');
$resolver->setAllowedTypes('user_hash_header', 'string');
$resolver->setAllowedTypes('ttl', 'int');
$resolver->setAllowedTypes('add_vary_on_hash', 'bool');
$resolver->setAllowedValues('user_hash_header', static function ($value): bool {
return '' !== $value;
});
$this->options = $resolver->resolve($options);
}
/**
* Return the response to the context hash request with a header containing
* the generated hash.
*
* If the ttl is bigger than 0, cache headers will be set for this response.
*/
public function onKernelRequest(RequestEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
$request = $event->getRequest();
if (!$this->requestMatcher->matches($request)) {
if ($request->headers->has($this->options['user_hash_header'])) {
// Keep track of if user is anonymous when we have user hash header in request
$this->wasAnonymous = $this->isAnonymous($request);
}
// Return early if request is not a hash lookup
return;
}
$hash = $this->hashGenerator->generateHash();
if ($this->responseTagger && $request->hasSession()) {
$tag = UserContextInvalidator::buildTag($request->getSession()->getId());
$this->responseTagger->addTags([$tag]);
}
// status needs to be 200 as otherwise varnish will not cache the response.
$response = new Response('', 200, [
$this->options['user_hash_header'] => $hash,
'Content-Type' => 'application/vnd.fos.user-context-hash',
]);
if ($this->options['ttl'] > 0) {
$response->setClientTtl($this->options['ttl']);
$response->setVary($this->options['user_identifier_headers']);
$response->setPublic();
if ($this->hasSessionListener) {
// header to avoid Symfony SessionListener overwriting the response to private
$response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, 1);
}
} else {
$response->setClientTtl(0);
$response->headers->addCacheControlDirective('no-cache');
}
$event->setResponse($response);
}
/**
* Tests if $request is an anonymous request or not.
*
* For backward compatibility reasons, true will be returned if no anonymous request matcher was provided.
*/
private function isAnonymous(Request $request): bool
{
return $this->anonymousRequestMatcher && $this->anonymousRequestMatcher->matches($request);
}
/**
* Add the context hash header to the headers to vary on if the header was
* present in the request.
*/
public function onKernelResponse(ResponseEvent $event): void
{
if (HttpKernelInterface::MAIN_REQUEST !== $event->getRequestType()) {
return;
}
$response = $event->getResponse();
$request = $event->getRequest();
$vary = $response->getVary();
if ($request->headers->has($this->options['user_hash_header'])) {
$requestHash = $request->headers->get($this->options['user_hash_header']);
// Generate hash to see if it might have changed during request if user was, or is "logged in" (session)
// But only needed if user was, or is, logged in
if (!$this->wasAnonymous || !$this->isAnonymous($request)) {
$hash = $this->hashGenerator->generateHash();
}
if (isset($hash) && $hash !== $requestHash) {
// hash has changed, session has most certainly changed, prevent setting incorrect cache
$response->setCache([
'max_age' => 0,
's_maxage' => 0,
'private' => true,
]);
$response->headers->addCacheControlDirective('no-cache');
$response->headers->addCacheControlDirective('no-store');
return;
}
if ($this->options['add_vary_on_hash']
&& !in_array($this->options['user_hash_header'], $vary, true)
) {
$vary[] = $this->options['user_hash_header'];
}
// user hash header was in vary or just added here by "add_vary_on_hash"
if ($this->hasSessionListener && in_array($this->options['user_hash_header'], $vary, true)) {
// header to avoid Symfony SessionListener overwriting the response to private
$response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER, 1);
}
} elseif ($this->options['add_vary_on_hash']) {
/*
* Additional precaution: If for some reason we get requests without a user hash, vary
* on user identifier headers to avoid the caching proxy mixing up caches between
* users. For the hash lookup request, those Vary headers are already added in
* onKernelRequest above.
*/
foreach ($this->options['user_identifier_headers'] as $header) {
if (!in_array($header, $vary, true)) {
$vary[] = $header;
}
}
}
$response->setVary($vary, true);
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::RESPONSE => 'onKernelResponse',
KernelEvents::REQUEST => ['onKernelRequest', 7],
];
}
}