Skip to content

Commit 776206a

Browse files
Merge pull request #616 from components-web-app/fix/mercure-cookie-foreign-host
Send no Mercure cookie on a host outside the hub's domain
2 parents 22f3fab + 4a82011 commit 776206a

17 files changed

Lines changed: 486 additions & 29 deletions

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ Every change that reaches `main` adds a line under **Unreleased**. When a versio
77
### Added
88
- `GET /_/layouts/{reference}` finds a layout by its `reference` as well as its UUID, the reference winning when both match, as for component groups; the response's `@id` stays the UUID IRI ([#615](https://github.com/components-web-app/api-components-bundle/pull/615))
99

10+
### Fixed
11+
- A request on a host that shares no registrable domain with the Mercure hub's public URL (a production alias, a tunnel) no longer 500s on login, JWT refresh, logout or a failed `/me`: no Mercure cookie is sent, a warning is logged, and only real-time is unavailable there ([#616](https://github.com/components-web-app/api-components-bundle/pull/616))
12+
1013
## [2.0.0-alpha.46](https://github.com/components-web-app/api-components-bundle/compare/2.0.0-alpha.45...2.0.0-alpha.46) - 2026-11-25
1114

1215
### Breaking

‎CLAUDE.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,7 @@ Resources are fetched and cached **individually**. Never embed related data outs
255255
- The cookie is `__Secure-mercure_access_token`. symfony/mercure throws when building it for a plain-HTTP `public_url`; a plain-HTTP setup sets a prefix-less `cookie_name` on the hub.
256256
- **The subscriber cookie and its token share the refresh token's lifetime** (#498): `MercureAuthorization` passes `exp` = now + `refresh_token.ttl` as an additional claim, which symfony/mercure (0.8 and 0.9) uses for both the token and the cookie, so the browser drops the cookie exactly when the hub would refuse it. `mercure.default_cookie_lifetime` does not apply to it. Pass `exp` as a `DateTimeImmutable`: an int is read as a relative lifetime for the cookie and is not accepted by lcobucci for the token. Re-issued on login and every JWT refresh, so a session slides; a clear (`getClearAuthorizationCookie()`) expires it.
257257
- **A clear expires the subscriber cookie, never re-issues it.** `MercureAuthorization::getClearAuthorizationCookie()` (logout, an invalid or expired JWT, a failed `/me`) is symfony/mercure's `createClearCookie()` with the bundle's SameSite, so it has the login cookie's name, path, domain and secure flag and reads nothing from the security context: `LogoutEvent` is dispatched before the firewall clears the token, so a cookie built from grants there carries the signed-out user's grants. Afterwards the browser holds no grants, like a visitor who never signed in. **A failed `/me` expires the Mercure cookie whenever the request carries it, with or without the JWT cookie**: the JWT cookie expires with the session, the Mercure cookie does not, so an expired session sends only the Mercure cookie. A failed `/me` carrying neither sets no cookie.
258+
- **A host outside the hub's domain gets no subscriber cookie, logged at warning, never a 500.** symfony/mercure refuses a cookie (set or clear) when the request host and the hub's `public_url` share no registrable domain (a production alias, a tunnel), throwing its `RuntimeException`. `MercureAuthorization::getAuthorizationCookie()`/`getClearAuthorizationCookie()` return `null` then, and every caller (login, refresh, logout, the JWT clear listeners) skips it, so the request carries on without real-time. The catch is that class only, rethrown unless `Utility\MercureCookieDomain::isOutside()`, which mirrors symfony/mercure's domain rule (`MercureCookieDomainTest` checks each case against the library), confirms the host is foreign: the token factory can throw the same class for a JWKS fetch. An `InvalidArgumentException` (JWT configuration, a `__Secure-` name over plain HTTP) always propagates.
258259
- **The public update is what an anonymous `GET` returns** (#494). `MercureResourcePublisher` gets it from `AnonymousResourceReader`: an internal `SUB_REQUEST` (`catch: false`) for the resource's IRI with the writer's cookies, `Authorization`, body and conditional headers stripped, and the token storage set to `null` for its duration and restored in a `finally`. The firewall never runs on a sub-request, so clearing the token is the only way to be anonymous there; never swap the token inside the writer's request itself. A 401/403/404 (or a security exception) means anonymous callers cannot read it. Anything else propagates.
259260
- **A public delete `{"@id"}` goes out only when the write itself took the resource from public to not public**, because a delete reveals the IRI (a route's IRI is its path). `MercureResourcePublisher::leftPublicInThisWrite()` decides it from the written entity's UoW change set, captured at `onFlush` (the change set is gone by `postFlush`, so a re-add keeps the first answer): a publication date or a Route's `liveAt` moving from active to inactive (future or null), a page's or page data's `route` unset, or its `parentPage`/`parentPageData` changed (then only if the anonymous read is denied). An unreadable resource with none of these gets nothing on the public topic; the private update still goes out. Never decide it with a before-state read. Descendants a write hides without being written get no message: a known limitation.
260261
- **Services that memoise caller-dependent answers on shared objects implement `Utility\CallerScopedStateInterface`** and are tagged `silverback.api_components.caller_scoped_state` (`RouteReachabilityResolver`, `ResourceMetadataProvider`): the reader isolates them for the sub-request and restores them after, because entities are shared with the writer through the identity map. A new memo keyed by an entity or `_metadata` whose answer depends on the token must join the tag. `RouteLiveResolver` memoises only dates, which are caller-independent.

‎src/EventListener/Jwt/JWTClearTokenListener.php‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,15 +60,17 @@ public function onKernelResponse(ResponseEvent $event): void
6060
$response->headers->setCookie($clearCookie);
6161
}
6262
$clearMercureCookie = $this->mercureAuthorization->getClearAuthorizationCookie();
63-
if ($hasJwtCookie || $request->cookies->has($clearMercureCookie->getName())) {
63+
if ($clearMercureCookie && ($hasJwtCookie || $request->cookies->has($clearMercureCookie->getName()))) {
6464
$response->headers->setCookie($clearMercureCookie);
6565
}
6666
}
6767

6868
private function clearJwtCookie(Response $response): void
6969
{
7070
$response->headers->setCookie($this->cookieProvider->createCookie('x.x.x', null, 1));
71-
$response->headers->setCookie($this->mercureAuthorization->getClearAuthorizationCookie());
71+
if ($clearMercureCookie = $this->mercureAuthorization->getClearAuthorizationCookie()) {
72+
$response->headers->setCookie($clearMercureCookie);
73+
}
7274
$this->collectorData?->recordJwtCookieCleared();
7375
}
7476
}

‎src/EventListener/Jwt/JWTEventListener.php‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,9 @@ public function __construct(
4242

4343
public function onJWTAuthenticationSuccess(AuthenticationSuccessEvent $event): void
4444
{
45-
$responseHeaders = $event->getResponse()->headers;
46-
$responseHeaders->setCookie($this->mercureAuthorization->getAuthorizationCookie());
45+
if ($mercureCookie = $this->mercureAuthorization->getAuthorizationCookie()) {
46+
$event->getResponse()->headers->setCookie($mercureCookie);
47+
}
4748
}
4849

4950
public function onJWTCreated(JWTCreatedEvent $event): void
@@ -89,7 +90,9 @@ public function onKernelResponse(ResponseEvent $event): void
8990
if (!empty($token)) {
9091
$responseHeaders = $event->getResponse()->headers;
9192
$responseHeaders->setCookie($this->cookieProvider->createCookie($token));
92-
$responseHeaders->setCookie($this->mercureAuthorization->getAuthorizationCookie());
93+
if ($mercureCookie = $this->mercureAuthorization->getAuthorizationCookie()) {
94+
$responseHeaders->setCookie($mercureCookie);
95+
}
9396
}
9497
}
9598
}

‎src/Mercure/MercureAuthorization.php‎

Lines changed: 39 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,16 @@
1515
use ApiPlatform\Metadata\HttpOperation;
1616
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
1717
use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
18+
use Psr\Log\LoggerInterface;
1819
use Silverback\ApiComponentsBundle\Helper\Publishable\PublishableStatusChecker;
1920
use Silverback\ApiComponentsBundle\Realtime\ApiResource\RealtimeEvent;
21+
use Silverback\ApiComponentsBundle\Utility\MercureCookieDomain;
2022
use Symfony\Component\ExpressionLanguage\Expression;
2123
use Symfony\Component\HttpFoundation\Cookie;
2224
use Symfony\Component\HttpFoundation\RequestStack;
2325
use Symfony\Component\Mercure\Authorization;
26+
use Symfony\Component\Mercure\Exception\RuntimeException as MercureRuntimeException;
27+
use Symfony\Component\Mercure\HubRegistry;
2428
use Symfony\Component\Routing\RequestContext;
2529
use Symfony\Component\Routing\RouterInterface;
2630
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
@@ -39,6 +43,7 @@ public function __construct(
3943
private readonly PublishableStatusChecker $publishableStatusChecker,
4044
private readonly RequestContext $requestContext,
4145
private readonly Authorization $mercureAuthorization,
46+
private readonly HubRegistry $hubRegistry,
4247
private readonly RequestStack $requestStack,
4348
private readonly AuthorizationCheckerInterface $authorizationChecker,
4449
private readonly RouterInterface $router,
@@ -47,24 +52,48 @@ public function __construct(
4752
private readonly ?string $hubName = null,
4853
private readonly bool $secureSubscriptions = false,
4954
private readonly bool $realtimeEnabled = true,
55+
private readonly ?LoggerInterface $logger = null,
5056
) {
5157
}
5258

53-
public function getAuthorizationCookie(): Cookie
59+
public function getAuthorizationCookie(): ?Cookie
5460
{
55-
$subscribeTopics = $this->getSubscribeTopics();
56-
$expiresAt = new \DateTimeImmutable(\sprintf('+%d seconds', $this->cookieLifetime));
61+
return $this->createWithinHubDomain(function (): Cookie {
62+
$subscribeTopics = $this->getSubscribeTopics();
63+
$expiresAt = new \DateTimeImmutable(\sprintf('+%d seconds', $this->cookieLifetime));
5764

58-
return $this->mercureAuthorization
59-
->createCookie($this->requestStack->getCurrentRequest(), ['urlpattern' => $subscribeTopics], null, ['exp' => $expiresAt], $this->hubName)
60-
->withSameSite($this->cookieSameSite);
65+
return $this->mercureAuthorization->createCookie($this->requestStack->getCurrentRequest(), ['urlpattern' => $subscribeTopics], null, ['exp' => $expiresAt], $this->hubName);
66+
});
6167
}
6268

63-
public function getClearAuthorizationCookie(): Cookie
69+
public function getClearAuthorizationCookie(): ?Cookie
6470
{
65-
return $this->mercureAuthorization
66-
->createClearCookie($this->requestStack->getCurrentRequest(), $this->hubName)
67-
->withSameSite($this->cookieSameSite);
71+
return $this->createWithinHubDomain(fn (): Cookie => $this->mercureAuthorization->createClearCookie($this->requestStack->getCurrentRequest(), $this->hubName));
72+
}
73+
74+
/**
75+
* @param \Closure(): Cookie $create
76+
*/
77+
private function createWithinHubDomain(\Closure $create): ?Cookie
78+
{
79+
try {
80+
$cookie = $create();
81+
} catch (MercureRuntimeException $exception) {
82+
$host = $this->requestStack->getCurrentRequest()?->getHost();
83+
$hubUrl = $this->hubRegistry->getHub($this->hubName)->getPublicUrl();
84+
if (null === $host || !MercureCookieDomain::isOutside($host, $hubUrl)) {
85+
throw $exception;
86+
}
87+
$this->logger?->warning('No Mercure subscriber cookie can be set for the host "{host}": it is outside the domain of the hub\'s public URL "{hub_url}", so real-time updates are unavailable on it.', [
88+
'host' => $host,
89+
'hub_url' => $hubUrl,
90+
'exception' => $exception,
91+
]);
92+
93+
return null;
94+
}
95+
96+
return $cookie->withSameSite($this->cookieSameSite);
6897
}
6998

7099
public function getSubscribeTopics(): array

‎src/Resources/config/services.php‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,7 @@
268268
use Symfony\Component\Mailer\Event\MessageEvent;
269269
use Symfony\Component\Mailer\MailerInterface;
270270
use Symfony\Component\Mercure\Authorization;
271+
use Symfony\Component\Mercure\HubRegistry;
271272
use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactoryInterface;
272273
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
273274
use Symfony\Component\Routing\RouterInterface;
@@ -1235,6 +1236,7 @@
12351236
new Reference(PublishableStatusChecker::class),
12361237
new Reference('router.request_context'),
12371238
new Reference(Authorization::class),
1239+
new Reference(HubRegistry::class),
12381240
new Reference('request_stack'),
12391241
new Reference(AuthorizationCheckerInterface::class),
12401242
new Reference(RouterInterface::class),
@@ -1243,6 +1245,7 @@
12431245
null,
12441246
false,
12451247
true,
1248+
new Reference('logger', ContainerInterface::NULL_ON_INVALID_REFERENCE),
12461249
]
12471250
);
12481251
$services->alias(MercureAuthorization::class, 'silverback.api_components.mercure.authorization');

‎src/Security/EventListener/AccessDeniedListener.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ public function onPostRespond(ResponseEvent $event): void
3636
return;
3737
}
3838
$clearMercureCookie = $this->mercureAuthorization->getClearAuthorizationCookie();
39-
if (!$request->cookies->has($clearMercureCookie->getName())) {
39+
if (!$clearMercureCookie || !$request->cookies->has($clearMercureCookie->getName())) {
4040
return;
4141
}
4242
$response->headers->setCookie($clearMercureCookie);

‎src/Security/EventListener/LogoutListener.php‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,9 @@ public function __invoke(LogoutEvent $event): void
3434
$this->storage->expireAll($event->getToken()->getUser());
3535
$response = $event->getResponse() ?? new Response();
3636
$response->headers->setCookie($this->cookieProvider->createCookie('x.x.x', null, 1));
37-
$response->headers->setCookie($this->mercureAuthorization->getClearAuthorizationCookie());
37+
if ($clearMercureCookie = $this->mercureAuthorization->getClearAuthorizationCookie()) {
38+
$response->headers->setCookie($clearMercureCookie);
39+
}
3840
$response->headers->remove('Location');
3941
$response->setStatusCode(Response::HTTP_OK)->setContent('');
4042
$event->setResponse($response);
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Silverback API Components Bundle Project
5+
*
6+
* (c) Daniel West <daniel@silverback.is>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Silverback\ApiComponentsBundle\Utility;
13+
14+
final class MercureCookieDomain
15+
{
16+
public static function isOutside(string $requestHost, string $hubPublicUrl): bool
17+
{
18+
$hubHost = parse_url($hubPublicUrl, \PHP_URL_HOST);
19+
if (!\is_string($hubHost)) {
20+
return false;
21+
}
22+
23+
$hubHost = strtolower($hubHost);
24+
$host = strtolower($requestHost);
25+
if ($hubHost === $host || str_ends_with($hubHost, '.' . $host)) {
26+
return false;
27+
}
28+
29+
$segments = explode('.', $host);
30+
for ($i = 0, $length = \count($segments) - 1; $i < $length; ++$i) {
31+
$domain = implode('.', \array_slice($segments, $i));
32+
if ($domain === $hubHost || str_ends_with($hubHost, '.' . $domain)) {
33+
return false;
34+
}
35+
}
36+
37+
return true;
38+
}
39+
}

‎tests/DependencyInjection/SilverbackApiComponentsExtensionTest.php‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@
8686
use Symfony\Component\DependencyInjection\Definition;
8787
use Symfony\Component\DependencyInjection\Reference;
8888
use Symfony\Component\HttpFoundation\Cookie;
89+
use Symfony\Component\Mercure\HubRegistry;
8990

9091
/**
9192
* The extension reads `user.email_verification` keys straight out of the processed configuration.
@@ -541,8 +542,12 @@ public function test_defaulted_configuration_reaches_the_services_that_consume_i
541542
self::assertSame("is_granted('ROLE_CMS_ADMIN')", $this->argument($container, $published, $argument));
542543
}
543544

544-
self::assertSame('%silverback.api_components.refresh_token.ttl%', $container->findDefinition(MercureAuthorization::class)->getArgument(8));
545-
self::assertSame('cookieLifetime', new \ReflectionMethod(MercureAuthorization::class, '__construct')->getParameters()[8]->getName());
545+
self::assertSame('%silverback.api_components.refresh_token.ttl%', $container->findDefinition(MercureAuthorization::class)->getArgument(9));
546+
self::assertSame('cookieLifetime', new \ReflectionMethod(MercureAuthorization::class, '__construct')->getParameters()[9]->getName());
547+
self::assertEquals(new Reference(HubRegistry::class), $container->findDefinition(MercureAuthorization::class)->getArgument(5));
548+
self::assertSame('hubRegistry', new \ReflectionMethod(MercureAuthorization::class, '__construct')->getParameters()[5]->getName());
549+
self::assertEquals(new Reference('logger', ContainerInterface::NULL_ON_INVALID_REFERENCE), $container->findDefinition(MercureAuthorization::class)->getArgument(14));
550+
self::assertSame('logger', new \ReflectionMethod(MercureAuthorization::class, '__construct')->getParameters()[14]->getName());
546551
self::assertSame(Cookie::SAMESITE_STRICT, $this->argument($container, MercureAuthorization::class, '$cookieSameSite'));
547552
self::assertNull($this->argument($container, MercureAuthorization::class, '$hubName'));
548553
self::assertNull($container->getParameter(RealtimeHubCompilerPass::HUB_NAME_PARAMETER));

0 commit comments

Comments
 (0)