feat: back-channel logout to client apps

This commit is contained in:
fromme committed 2026-11-13 16:20:22 +01:00
1 parent 3247df1171
commit aebfc2ca9b
4 files changed
+303

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20261113151744 extends AbstractMigration
{
public function getDescription(): string
{
return 'Adds the back-channel logout URL and secret to OAuth2 clients.';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE oauth2_client ADD logout_url VARCHAR(255) DEFAULT NULL, ADD logout_secret VARCHAR(128) DEFAULT NULL');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE oauth2_client DROP logout_url, DROP logout_secret');
}
}
+39
View File
@@ -50,6 +50,21 @@ class OAuth2Client extends AbstractClient
#[ORM\Column(type: 'json')]
private array $requiredRoles = [];
/**
* Where BackchannelLogoutListener tells this client that an account logged out of
* MyE&P. Null for a client that has no back channel, which is then simply not told.
*/
#[ORM\Column(type: 'string', length: 255, nullable: true)]
private ?string $logoutUrl = null;
/**
* The bearer token sent with the back-channel logout call. Stored readable, unlike the
* client secret, because MyE&P is the side that sends it rather than the side that
* checks it.
*/
#[ORM\Column(type: 'string', length: 128, nullable: true)]
private ?string $logoutSecret = null;
/**
* @return list<string>
*/
@@ -67,4 +82,28 @@ class OAuth2Client extends AbstractClient
return $this;
}
public function getLogoutUrl(): ?string
{
return $this->logoutUrl;
}
public function setLogoutUrl(?string $logoutUrl): self
{
$this->logoutUrl = $logoutUrl;
return $this;
}
public function getLogoutSecret(): ?string
{
return $this->logoutSecret;
}
public function setLogoutSecret(?string $logoutSecret): self
{
$this->logoutSecret = $logoutSecret;
return $this;
}
}
@@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
namespace App\EventListener;
use App\Entity\OAuth2Client;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\Security\Http\Event\LogoutEvent;
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
* Tells every client application with a back channel that an account logged out of MyE&P,
* so the application can end that account's sessions as well.
*
* Each client gets a form-encoded POST of the account's `sub` — the uuid, exactly as
* /api/userinfo exports it — authorized with the client's own logout secret. The call is
* best effort: a client that is down, slow or misconfigured is logged and skipped, because
* a failed call must never keep the user signed in to MyE&P.
*
* Only an explicit logout gets here. A session that merely expires dispatches nothing, so
* the client applications are not told about it.
*
* Runs before SessionLogoutListener (priority 0), which invalidates the session the
* `_oauth2` flag is read from.
*/
#[AsEventListener(event: LogoutEvent::class, priority: 64)]
class BackchannelLogoutListener
{
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly HttpClientInterface $httpClient,
private readonly LoggerInterface $authLogger,
) {
}
public function __invoke(LogoutEvent $event): void
{
$user = $event->getToken()?->getUser();
if (false === $user instanceof User) {
return;
}
// AuthorizationCodeListener logs the user out of MyE&P straight after authorizing an
// application that sent them here to sign in. Telling the applications about that
// logout would sign the user out of the very application they just signed in to.
if ($event->getRequest()->hasSession() && true === $event->getRequest()->getSession()->get('_oauth2', false)) {
return;
}
// a handful of rows, so filtered here rather than in a query
$clients = array_filter(
$this->entityManager->getRepository(OAuth2Client::class)->findAll(),
static fn (OAuth2Client $client): bool => null !== $client->getLogoutUrl(),
);
// Requests first, responses second: HttpClient sends concurrently, so a slow client
// costs its own timeout once rather than adding it to every other client's.
$responses = [];
foreach ($clients as $client) {
try {
$responses[] = [$client, $this->httpClient->request('POST', (string) $client->getLogoutUrl(), [
'auth_bearer' => (string) $client->getLogoutSecret(),
'body' => ['sub' => $user->getUuid()],
'timeout' => 3,
])];
} catch (ExceptionInterface $e) {
// a malformed URL is refused before anything is sent
$this->warn($client, $user, ['error' => $e->getMessage()]);
}
}
foreach ($responses as [$client, $response]) {
try {
$status = $response->getStatusCode();
} catch (ExceptionInterface $e) {
$this->warn($client, $user, ['error' => $e->getMessage()]);
continue;
}
if (200 !== $status) {
$this->warn($client, $user, ['status' => $status]);
}
}
}
/**
* @param array<string, mixed> $context
*/
private function warn(OAuth2Client $client, User $user, array $context): void
{
$this->authLogger->warning('Back-channel logout failed', [
'client' => $client->getName(),
'user_id' => $user->getId(),
] + $context);
}
}
@@ -0,0 +1,135 @@
<?php
declare(strict_types=1);
namespace App\Tests\EventListener;
use App\Entity\OAuth2Client;
use App\Entity\User;
use App\EventListener\BackchannelLogoutListener;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Event\LogoutEvent;
class BackchannelLogoutListenerTest extends TestCase
{
public function testPostsTheSubFormEncodedWithTheClientSecret(): void
{
$user = new User('[email protected]');
$calls = [];
$http = new MockHttpClient(static function (string $method, string $url, array $options) use (&$calls): MockResponse {
$calls[] = compact('method', 'url', 'options');
return new MockResponse('', ['http_code' => 200]);
});
$this->listener([$this->client('https://ephub.test/auth/backchannel-logout', 's3cret')], $http)
->__invoke($this->event($user));
self::assertCount(1, $calls);
self::assertSame('POST', $calls[0]['method']);
self::assertSame('https://ephub.test/auth/backchannel-logout', $calls[0]['url']);
self::assertContains('Authorization: Bearer s3cret', $calls[0]['options']['headers']);
self::assertContains('Content-Type: application/x-www-form-urlencoded', $calls[0]['options']['headers']);
self::assertSame('sub='.$user->getUuid(), $calls[0]['options']['body']);
}
public function testFailingClientIsLoggedAndTheOthersAreStillCalled(): void
{
$calls = 0;
$http = new MockHttpClient([
static function () use (&$calls): MockResponse {
++$calls;
return new MockResponse('', ['error' => 'Connection timed out']);
},
static function () use (&$calls): MockResponse {
++$calls;
return new MockResponse('', ['http_code' => 401]);
},
static function () use (&$calls): MockResponse {
++$calls;
return new MockResponse('', ['http_code' => 200]);
},
]);
$logger = $this->createMock(LoggerInterface::class);
$logger->expects(self::exactly(2))->method('warning');
$this->listener([
$this->client('https://a.test/logout', 'a'),
$this->client('https://b.test/logout', 'b'),
$this->client('https://c.test/logout', 'c'),
], $http, $logger)->__invoke($this->event(new User('[email protected]')));
self::assertSame(3, $calls);
}
public function testMalformedUrlIsLoggedInsteadOfThrown(): void
{
$logger = $this->createMock(LoggerInterface::class);
$logger->expects(self::once())->method('warning');
$this->listener([$this->client('ftp://ephub.test/logout', 'a')], new MockHttpClient(), $logger)
->__invoke($this->event(new User('[email protected]')));
}
public function testLogoutAfterAnExternalAuthorizationTellsNobody(): void
{
$http = new MockHttpClient(static fn (): MockResponse => self::fail('No client may be called'));
$this->listener([$this->client('https://ephub.test/logout', 's')], $http)
->__invoke($this->event(new User('[email protected]'), external: true));
$this->addToAssertionCount(1);
}
public function testLogoutWithoutTokenTellsNobody(): void
{
$http = new MockHttpClient(static fn (): MockResponse => self::fail('No client may be called'));
$this->listener([$this->client('https://ephub.test/logout', 's')], $http)
->__invoke(new LogoutEvent(new Request(), null));
$this->addToAssertionCount(1);
}
private function client(string $logoutUrl, string $logoutSecret): OAuth2Client
{
return (new OAuth2Client('EPHub', md5($logoutUrl), 'secret'))
->setLogoutUrl($logoutUrl)
->setLogoutSecret($logoutSecret);
}
/**
* @param list<OAuth2Client> $clients
*/
private function listener(array $clients, MockHttpClient $http, ?LoggerInterface $logger = null): BackchannelLogoutListener
{
$repository = self::createStub(EntityRepository::class);
$repository->method('findAll')->willReturn($clients);
$entityManager = self::createStub(EntityManagerInterface::class);
$entityManager->method('getRepository')->willReturn($repository);
return new BackchannelLogoutListener($entityManager, $http, $logger ?? self::createStub(LoggerInterface::class));
}
private function event(User $user, bool $external = false): LogoutEvent
{
$request = new Request();
$session = new Session(new MockArraySessionStorage());
$session->set('_oauth2', $external);
$request->setSession($session);
return new LogoutEvent($request, new UsernamePasswordToken($user, 'main', $user->getRoles()));
}
}