From aebfc2ca9b6f038faeab2a30d7f6144ab46ec80e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Fromme?= Date: Fri, 13 Nov 2026 16:20:22 +0100 Subject: [PATCH] feat: back-channel logout to client apps --- migrations/Version20261113151744.php | 26 ++++ src/Entity/OAuth2Client.php | 39 +++++ .../BackchannelLogoutListener.php | 103 +++++++++++++ .../BackchannelLogoutListenerTest.php | 135 ++++++++++++++++++ 4 files changed, 303 insertions(+) create mode 100644 migrations/Version20261113151744.php create mode 100644 src/EventListener/BackchannelLogoutListener.php create mode 100644 tests/EventListener/BackchannelLogoutListenerTest.php diff --git a/migrations/Version20261113151744.php b/migrations/Version20261113151744.php new file mode 100644 index 00000000..0d3dff7f --- /dev/null +++ b/migrations/Version20261113151744.php @@ -0,0 +1,26 @@ +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'); + } +} diff --git a/src/Entity/OAuth2Client.php b/src/Entity/OAuth2Client.php index af9aaa89..78896134 100644 --- a/src/Entity/OAuth2Client.php +++ b/src/Entity/OAuth2Client.php @@ -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 */ @@ -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; + } } diff --git a/src/EventListener/BackchannelLogoutListener.php b/src/EventListener/BackchannelLogoutListener.php new file mode 100644 index 00000000..517e2777 --- /dev/null +++ b/src/EventListener/BackchannelLogoutListener.php @@ -0,0 +1,103 @@ +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 $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); + } +} diff --git a/tests/EventListener/BackchannelLogoutListenerTest.php b/tests/EventListener/BackchannelLogoutListenerTest.php new file mode 100644 index 00000000..225f8052 --- /dev/null +++ b/tests/EventListener/BackchannelLogoutListenerTest.php @@ -0,0 +1,135 @@ + 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('someone@example.org'))); + + 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('someone@example.org'))); + } + + 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('someone@example.org'), 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 $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())); + } +}