From 916ef3662ec06a7b4130bd22708f1fbd07fd2acc Mon Sep 17 00:00:00 2001 From: Timon Heuser Date: Wed, 4 Nov 2026 13:47:05 +0100 Subject: [PATCH 1/5] SECURITY: use flows native login function for passwordless login --- .../PasswordlessLoginController.php | 61 +++--- .../WebAuthnPasswordlessProvider.php | 127 ++++++++++-- .../Token/WebAuthnPasswordlessToken.php | 30 +-- .../SecondFactor/Service/WebAuthnService.php | 5 + Configuration/Settings.yaml | 7 +- Resources/Public/JavaScript/webauthn.js | 18 +- Tests/E2E/steps/general-login.steps.ts | 3 +- .../WebAuthnPasswordlessProviderTest.php | 184 ++++++++++++++++++ .../Service/WebAuthnServiceTest.php | 14 ++ 9 files changed, 379 insertions(+), 70 deletions(-) create mode 100644 Tests/Unit/SecondFactor/Security/WebAuthnPasswordlessProviderTest.php diff --git a/Classes/SecondFactor/Controller/PasswordlessLoginController.php b/Classes/SecondFactor/Controller/PasswordlessLoginController.php index a03c872..21edc78 100644 --- a/Classes/SecondFactor/Controller/PasswordlessLoginController.php +++ b/Classes/SecondFactor/Controller/PasswordlessLoginController.php @@ -9,9 +9,9 @@ use Neos\Flow\Annotations as Flow; use Neos\Flow\Mvc\Controller\ActionController; use Neos\Flow\Mvc\View\JsonView; -use Neos\Flow\Security\Authentication\TokenInterface; +use Neos\Flow\Security\Authentication\AuthenticationManagerInterface; use Neos\Flow\Security\Context as SecurityContext; -use Sandstorm\BackendUserManagement\SecondFactor\Domain\AuthenticationStatus; +use Neos\Flow\Security\Exception\AuthenticationRequiredException; use Sandstorm\BackendUserManagement\SecondFactor\Security\Token\WebAuthnPasswordlessToken; use Sandstorm\BackendUserManagement\SecondFactor\Service\SecondFactorSessionStorageService; use Sandstorm\BackendUserManagement\SecondFactor\Service\WebAuthnService; @@ -22,7 +22,9 @@ * Both actions are reachable while logged out (this controller is intentionally NOT behind * the Neos.Neos:Backend request pattern). They are hard-gated by the * `secondFactor.webAuthn.passwordlessLoginEnabled` setting (off by default) so that, while disabled, no - * one can authenticate through this path even if the UI button were somehow present. + * one can authenticate through this path even if the UI button were somehow present. The + * {@see \Sandstorm\BackendUserManagement\SecondFactor\Security\Authentication\WebAuthnPasswordlessProvider} + * checks the setting again, as its token is active on every request. */ class PasswordlessLoginController extends ActionController { @@ -36,6 +38,12 @@ class PasswordlessLoginController extends ActionController */ protected $securityContext; + /** + * @Flow\Inject + * @var AuthenticationManagerInterface + */ + protected $authenticationManager; + /** * @Flow\Inject * @var WebAuthnService @@ -80,55 +88,32 @@ public function optionsAction(): string } /** - * Ceremony step 2: verify the assertion, resolve the account, authenticate the parallel - * WebAuthn token (which logs the user into the Neos backend without a password), and - * return the URI for the client to redirect to. + * Ceremony step 2: the assertion arrives as the internal argument + * {@see WebAuthnPasswordlessToken::ASSERTION_FIELD}, which puts the token into AUTHENTICATION_NEEDED. + * Flow's AuthenticationManager then runs the WebAuthnPasswordlessProvider (verification, session id + * renewal, session tagging). Here we only report the outcome and the URI to redirect to. * * @Flow\SkipCsrfProtection */ - public function verifyAction(string $assertion): string + public function verifyAction(): string { if (!$this->passwordlessLoginEnabled) { return $this->jsonError('Passwordless login is disabled', 403); } - $serialized = $this->secondFactorSessionStorageService->getValue( - SecondFactorSessionStorageService::SESSION_OBJECT_WEBAUTHN_PASSWORDLESS_OPTIONS - ); - if (!is_string($serialized)) { - return $this->jsonError('No passwordless login in progress', 400); - } - $options = $this->webAuthnService->requestOptionsFromJson($serialized); - try { - $account = $this->webAuthnService->verifyPasswordlessAssertion( - $assertion, - $options, - $this->request->getHttpRequest() - ); - } catch (\Throwable $e) { - return $this->jsonError($e->getMessage(), 400); + // usually already done by the PolicyEnforcement interceptor - a no-op then + $this->authenticationManager->authenticate(); + } catch (AuthenticationRequiredException) { + // evaluated via the token below } $token = $this->securityContext->getAuthenticationTokensOfType(WebAuthnPasswordlessToken::class)[0] ?? null; - if ($token === null) { - return $this->jsonError('Passwordless authentication token not available', 500); + if ($token === null || !$token->isAuthenticated()) { + // the reason is in the security log - don't hand webauthn-lib details to the client + return $this->jsonError('Passkey login failed', 401); } - // Authenticate the parallel token with the resolved backend account and persist it to - // the session so the authentication survives the redirect to the backend. - $token->setAccount($account); - $token->setAuthenticationStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL); - $this->securityContext->refreshTokens(); - - // A user-verified passkey is itself multi-factor, so it also satisfies the 2FA gate. - $this->secondFactorSessionStorageService->initializeTwoFactorSessionObject(); - $this->secondFactorSessionStorageService->setAuthenticationStatus(AuthenticationStatus::AUTHENTICATED); - - $this->secondFactorSessionStorageService->removeValue( - SecondFactorSessionStorageService::SESSION_OBJECT_WEBAUTHN_PASSWORDLESS_OPTIONS - ); - $this->response->setContentType('application/json'); return json_encode([ 'status' => 'ok', diff --git a/Classes/SecondFactor/Security/Authentication/WebAuthnPasswordlessProvider.php b/Classes/SecondFactor/Security/Authentication/WebAuthnPasswordlessProvider.php index 1305f5d..add51b0 100644 --- a/Classes/SecondFactor/Security/Authentication/WebAuthnPasswordlessProvider.php +++ b/Classes/SecondFactor/Security/Authentication/WebAuthnPasswordlessProvider.php @@ -2,24 +2,66 @@ namespace Sandstorm\BackendUserManagement\SecondFactor\Security\Authentication; +use Neos\Flow\Annotations as Flow; +use Neos\Flow\Core\Bootstrap; +use Neos\Flow\Http\HttpRequestHandlerInterface; +use Neos\Flow\Http\ServerRequestAttributes; use Neos\Flow\Security\Authentication\Provider\AbstractProvider; use Neos\Flow\Security\Authentication\TokenInterface; +use Neos\Flow\Security\Exception\UnsupportedAuthenticationTokenException; +use Psr\Http\Message\ServerRequestInterface; +use Psr\Log\LoggerInterface; +use Sandstorm\BackendUserManagement\SecondFactor\Domain\AuthenticationStatus; use Sandstorm\BackendUserManagement\SecondFactor\Security\Token\WebAuthnPasswordlessToken; +use Sandstorm\BackendUserManagement\SecondFactor\Service\SecondFactorSessionStorageService; +use Sandstorm\BackendUserManagement\SecondFactor\Service\WebAuthnService; /** * Authentication provider for usernameless passwordless passkey login. * - * The actual WebAuthn verification and token authentication happen in the - * {@see \Sandstorm\BackendUserManagement\SecondFactor\Controller\PasswordlessLoginController} - * (it needs the session-stored challenge and the webauthn-lib validator). This provider - * exists so the framework registers the {@see WebAuthnPasswordlessToken} for this provider - * name, keeps it active (no request pattern), and restores it from the session on later - * requests. With the `oneToken` authentication strategy, an authenticated parallel token is - * enough for the request to count as authenticated; the resolved account is a regular - * `Neos.Neos:Backend` account, so roles and the current Neos user resolve normally. + * Verifies the WebAuthn assertion carried by the {@see WebAuthnPasswordlessToken} against the challenge + * stored in the session by {@see \Sandstorm\BackendUserManagement\SecondFactor\Controller\PasswordlessLoginController::optionsAction()}. + * It runs inside Flow's AuthenticationProviderManager, which on success renews the session id and tags the + * session with the account (so Neos can destroy it on deactivate / delete / password change). + * + * With the `oneToken` authentication strategy an authenticated parallel token is enough for the request to + * count as authenticated; the resolved account is a regular `Neos.Neos:Backend` account, so roles and the + * current Neos user resolve normally. */ class WebAuthnPasswordlessProvider extends AbstractProvider { + private const LOGGING_PREFIX = 'Sandstorm/BackendUserManagement: '; + + /** + * @Flow\Inject + * @var WebAuthnService + */ + protected $webAuthnService; + + /** + * @Flow\Inject + * @var SecondFactorSessionStorageService + */ + protected $secondFactorSessionStorageService; + + /** + * @Flow\Inject + * @var Bootstrap + */ + protected $bootstrap; + + /** + * @Flow\Inject(name="Neos.Flow:SecurityLogger") + * @var LoggerInterface + */ + protected $securityLogger; + + /** + * @Flow\InjectConfiguration(path="secondFactor.webAuthn.passwordlessLoginEnabled", package="Sandstorm.BackendUserManagement") + * @var bool + */ + protected $passwordlessLoginEnabled = false; + /** * @return array */ @@ -29,18 +71,75 @@ public function getTokenClassNames() } /** - * The AuthenticationProviderManager only calls this for tokens in state - * AUTHENTICATION_NEEDED. The controller drives this token straight from - * NO_CREDENTIALS_GIVEN to AUTHENTICATION_SUCCESSFUL, so there is nothing to do here: - * never downgrade an already-successful (session-restored) token. + * Only called by the AuthenticationProviderManager for tokens in state AUTHENTICATION_NEEDED, i.e. when the + * request carried an assertion (see WebAuthnPasswordlessToken::updateCredentials()). */ public function authenticate(TokenInterface $authenticationToken) { if (!$authenticationToken instanceof WebAuthnPasswordlessToken) { + throw new UnsupportedAuthenticationTokenException( + sprintf('This provider cannot authenticate the given token "%s".', get_class($authenticationToken)), + 1793795726 + ); + } + + $httpRequest = $this->currentHttpRequest(); + + // The token is active on every request - so this is checked here, not only in the controller. + if (!$this->passwordlessLoginEnabled) { + $this->rejectLogin($authenticationToken, 'passwordless login is disabled', $httpRequest); + return; + } + + $assertion = $authenticationToken->getCredentials()['assertion'] ?? null; + $serializedOptions = $this->secondFactorSessionStorageService->getValue( + SecondFactorSessionStorageService::SESSION_OBJECT_WEBAUTHN_PASSWORDLESS_OPTIONS + ); + if (!is_string($assertion) || !is_string($serializedOptions) || $httpRequest === null) { + $this->rejectLogin($authenticationToken, 'no passwordless login in progress', $httpRequest); return; } - if ($authenticationToken->getAuthenticationStatus() !== TokenInterface::AUTHENTICATION_SUCCESSFUL) { - $authenticationToken->setAuthenticationStatus(TokenInterface::NO_CREDENTIALS_GIVEN); + // Single use: the challenge is gone after one verification attempt, whatever its outcome. + $this->secondFactorSessionStorageService->removeValue( + SecondFactorSessionStorageService::SESSION_OBJECT_WEBAUTHN_PASSWORDLESS_OPTIONS + ); + + try { + $account = $this->webAuthnService->verifyPasswordlessAssertion( + $assertion, + $this->webAuthnService->requestOptionsFromJson($serializedOptions), + $httpRequest + ); + } catch (\Throwable $exception) { + $this->rejectLogin( + $authenticationToken, + sprintf('%s (%s)', $exception->getMessage(), $exception->getCode()), + $httpRequest + ); + return; } + + $authenticationToken->setAccount($account); + $authenticationToken->setAuthenticationStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL); + + // A user-verified passkey is itself multi-factor, so it also satisfies the 2FA gate. + $this->secondFactorSessionStorageService->initializeTwoFactorSessionObject(); + $this->secondFactorSessionStorageService->setAuthenticationStatus(AuthenticationStatus::AUTHENTICATED); + } + + private function rejectLogin(WebAuthnPasswordlessToken $token, string $reason, ?ServerRequestInterface $httpRequest): void + { + $token->setAuthenticationStatus(TokenInterface::WRONG_CREDENTIALS); + $clientIp = $httpRequest?->getAttribute(ServerRequestAttributes::CLIENT_IP); + $this->securityLogger->warning( + self::LOGGING_PREFIX . 'Passwordless passkey login failed: ' . $reason, + ['clientIp' => is_string($clientIp) ? $clientIp : 'unknown'] + ); + } + + private function currentHttpRequest(): ?ServerRequestInterface + { + $requestHandler = $this->bootstrap->getActiveRequestHandler(); + return $requestHandler instanceof HttpRequestHandlerInterface ? $requestHandler->getHttpRequest() : null; } } diff --git a/Classes/SecondFactor/Security/Token/WebAuthnPasswordlessToken.php b/Classes/SecondFactor/Security/Token/WebAuthnPasswordlessToken.php index d2d029c..3d29ca0 100644 --- a/Classes/SecondFactor/Security/Token/WebAuthnPasswordlessToken.php +++ b/Classes/SecondFactor/Security/Token/WebAuthnPasswordlessToken.php @@ -4,26 +4,34 @@ use Neos\Flow\Mvc\ActionRequest; use Neos\Flow\Security\Authentication\Token\AbstractToken; +use Neos\Utility\ObjectAccess; /** * Authentication token for usernameless, passwordless passkey login. * - * Unlike the username/password token, this token carries no credentials extracted - * from the request: the WebAuthn assertion is verified by the - * {@see \Sandstorm\BackendUserManagement\SecondFactor\Controller\PasswordlessLoginController}, - * which then sets the resolved account on this token and marks it authenticated. + * Works like Flow's UsernamePassword token: it picks the WebAuthn assertion up from a namespaced + * internal POST argument and marks itself AUTHENTICATION_NEEDED, so the regular + * AuthenticationProviderManager runs the * {@see \Sandstorm\BackendUserManagement\SecondFactor\Security\Authentication\WebAuthnPasswordlessProvider} - * is registered for this token so the framework instantiates and persists it. + * - including session id renewal and session tagging on success. + * + * The argument is namespaced on purpose: the token has no request pattern, so it is active on every + * request. A plain `assertion` argument would also match the 2nd-factor WebAuthn endpoint. */ class WebAuthnPasswordlessToken extends AbstractToken { - /** - * No credentials are read from the request — the controller performs the WebAuthn - * ceremony and authenticates this token directly. Must NOT change the authentication - * status here, otherwise refreshTokens() (which calls updateCredentials on every active - * token) would reset a token the controller just authenticated. - */ + public const ASSERTION_FIELD = '__authentication.Sandstorm.BackendUserManagement.Passwordless.assertion'; + public function updateCredentials(ActionRequest $actionRequest) { + if ($actionRequest->getHttpRequest()->getMethod() !== 'POST') { + return; + } + $allArguments = array_merge($actionRequest->getArguments(), $actionRequest->getInternalArguments()); + $assertion = ObjectAccess::getPropertyPath($allArguments, self::ASSERTION_FIELD); + if (is_string($assertion) && $assertion !== '') { + $this->credentials['assertion'] = $assertion; + $this->setAuthenticationStatus(self::AUTHENTICATION_NEEDED); + } } } diff --git a/Classes/SecondFactor/Service/WebAuthnService.php b/Classes/SecondFactor/Service/WebAuthnService.php index ce30663..6f5f784 100644 --- a/Classes/SecondFactor/Service/WebAuthnService.php +++ b/Classes/SecondFactor/Service/WebAuthnService.php @@ -361,6 +361,11 @@ public function resolveBackendAccountByUserHandle(string $userHandle): Account if ($account->getAuthenticationProviderName() !== 'Neos.Neos:Backend') { throw new \RuntimeException('Passkey does not belong to a Neos backend account', 1751200003); } + // Guard: a deactivated (expired) account must not log in - the password provider checks this via + // AccountRepository::findActiveByAccountIdentifierAndAuthenticationProviderName(), we have to do it ourselves. + if (!$account->isActive()) { + throw new \RuntimeException('Passkey belongs to an inactive account', 1793795361); + } return $account; } diff --git a/Configuration/Settings.yaml b/Configuration/Settings.yaml index f14ac5e..73742fb 100644 --- a/Configuration/Settings.yaml +++ b/Configuration/Settings.yaml @@ -58,9 +58,10 @@ Neos: patternOptions: controllerObjectNamePattern: 'Sandstorm\BackendUserManagement\SecondFactor\Controller\(LoginController|ModuleController)' # Parallel provider for usernameless passwordless passkey login. It has NO request - # pattern, so its token is always active and can be authenticated in-request by the - # PasswordlessLoginController; and NO entry point, so the existing Neos.Neos:Backend - # WebRedirect still serves the login screen. With Neos' `oneToken` strategy, an + # pattern, so its token is always active and is authenticated by Flow's + # AuthenticationProviderManager as soon as a POST carries the namespaced assertion + # (WebAuthnPasswordlessToken::ASSERTION_FIELD); and NO entry point, so the existing + # Neos.Neos:Backend WebRedirect still serves the login screen. With Neos' `oneToken` strategy, an # authenticated token here logs the (Neos.Neos:Backend) account into the backend. 'Sandstorm.BackendUserManagement:PasswordlessWebAuthn': provider: 'Sandstorm\BackendUserManagement\SecondFactor\Security\Authentication\WebAuthnPasswordlessProvider' diff --git a/Resources/Public/JavaScript/webauthn.js b/Resources/Public/JavaScript/webauthn.js index 08ae942..da7954c 100644 --- a/Resources/Public/JavaScript/webauthn.js +++ b/Resources/Public/JavaScript/webauthn.js @@ -149,7 +149,19 @@ } } - async function runAuthentication(container) { + // Body of the 2nd-factor verify request: a plain action argument. + function secondFactorAssertionBody(assertionJson) { + return { assertion: assertionJson }; + } + + // Body of the passwordless verify request: a namespaced internal argument, picked up by + // WebAuthnPasswordlessToken::updateCredentials() (see its ASSERTION_FIELD) - Flow's + // AuthenticationProviderManager then authenticates it like a username/password login. + function passwordlessAssertionBody(assertionJson) { + return { __authentication: { Sandstorm: { BackendUserManagement: { Passwordless: { assertion: assertionJson } } } } }; + } + + async function runAuthentication(container, buildBody) { clearError(container); var trigger = container.querySelector('[data-webauthn-trigger]'); if (trigger) trigger.disabled = true; @@ -160,7 +172,7 @@ }); if (!credential) throw new Error('No credential returned by browser'); var encoded = encodeAssertion(credential); - var result = await postJson(container.dataset.verifyUrl, { assertion: JSON.stringify(encoded) }); + var result = await postJson(container.dataset.verifyUrl, (buildBody || secondFactorAssertionBody)(JSON.stringify(encoded))); window.location.href = (result && result.redirect) ? result.redirect : '/neos'; } catch (e) { showError(container, describeError(container, e)); @@ -201,7 +213,7 @@ document.querySelectorAll('[data-webauthn-passwordless]').forEach(function (container) { if (!checkSupport(container)) return; var trigger = container.querySelector('[data-webauthn-trigger]'); - if (trigger) trigger.addEventListener('click', function () { runAuthentication(container); }); + if (trigger) trigger.addEventListener('click', function () { runAuthentication(container, passwordlessAssertionBody); }); }); } diff --git a/Tests/E2E/steps/general-login.steps.ts b/Tests/E2E/steps/general-login.steps.ts index b58510b..557cdd4 100644 --- a/Tests/E2E/steps/general-login.steps.ts +++ b/Tests/E2E/steps/general-login.steps.ts @@ -58,7 +58,8 @@ Then('the passwordless verify endpoint is forbidden', async ({ page }) => { // The endpoint must reject everyone while passwordless login is disabled — server-side, // not just by hiding the button. const response = await page.request.post('/neos/passwordless-webauthn/verify', { - data: { assertion: '{}' }, + // same body shape as webauthn.js, so the WebAuthnPasswordlessToken picks it up + data: { __authentication: { Sandstorm: { BackendUserManagement: { Passwordless: { assertion: '{}' } } } } }, failOnStatusCode: false, }); expect(response.status()).toBe(403); diff --git a/Tests/Unit/SecondFactor/Security/WebAuthnPasswordlessProviderTest.php b/Tests/Unit/SecondFactor/Security/WebAuthnPasswordlessProviderTest.php new file mode 100644 index 0000000..0f2b43a --- /dev/null +++ b/Tests/Unit/SecondFactor/Security/WebAuthnPasswordlessProviderTest.php @@ -0,0 +1,184 @@ +provider = WebAuthnPasswordlessProvider::create('Sandstorm.BackendUserManagement:PasswordlessWebAuthn', []); + + $this->webAuthnService = $this->createMock(WebAuthnService::class); + $this->webAuthnService->method('requestOptionsFromJson') + ->willReturn(PublicKeyCredentialRequestOptions::create(random_bytes(32))); + $this->sessionStorage = $this->createMock(SecondFactorSessionStorageService::class); + $this->securityLogger = $this->createMock(LoggerInterface::class); + + $this->httpRequest = (new ServerRequest('POST', 'https://neos.example/neos/passwordless-webauthn/verify')) + ->withAttribute(ServerRequestAttributes::CLIENT_IP, '203.0.113.7'); + $requestHandler = $this->createMock(HttpRequestHandlerInterface::class); + $requestHandler->method('getHttpRequest')->willReturn($this->httpRequest); + $bootstrap = $this->createMock(Bootstrap::class); + $bootstrap->method('getActiveRequestHandler')->willReturn($requestHandler); + + $this->inject($this->provider, 'webAuthnService', $this->webAuthnService); + $this->inject($this->provider, 'secondFactorSessionStorageService', $this->sessionStorage); + $this->inject($this->provider, 'bootstrap', $bootstrap); + $this->inject($this->provider, 'securityLogger', $this->securityLogger); + $this->inject($this->provider, 'passwordlessLoginEnabled', true); + } + + #[Test] + public function authenticatesTheAccountOfAValidAssertion(): void + { + $account = $this->createMock(Account::class); + $this->sessionStorage->method('getValue')->willReturn('{"stored":"options"}'); + $this->webAuthnService->expects(self::once())->method('verifyPasswordlessAssertion') + ->with('the-assertion', self::anything(), $this->httpRequest) + ->willReturn($account); + $this->sessionStorage->expects(self::once())->method('setAuthenticationStatus')->with(AuthenticationStatus::AUTHENTICATED); + $this->securityLogger->expects(self::never())->method('warning'); + + $token = $this->tokenWithAssertion('the-assertion'); + $this->provider->authenticate($token); + + self::assertSame(TokenInterface::AUTHENTICATION_SUCCESSFUL, $token->getAuthenticationStatus()); + self::assertSame($account, $token->getAccount()); + } + + #[Test] + public function rejectsAndLogsAFailedVerification(): void + { + $this->sessionStorage->method('getValue')->willReturn('{"stored":"options"}'); + $this->webAuthnService->method('verifyPasswordlessAssertion') + ->willThrowException(new \RuntimeException('Passkey belongs to an inactive account', 1793795361)); + $this->sessionStorage->expects(self::never())->method('setAuthenticationStatus'); + $this->securityLogger->expects(self::once())->method('warning')->with( + self::stringContains('Passkey belongs to an inactive account (1793795361)'), + ['clientIp' => '203.0.113.7'] + ); + + $token = $this->tokenWithAssertion('the-assertion'); + $this->provider->authenticate($token); + + self::assertSame(TokenInterface::WRONG_CREDENTIALS, $token->getAuthenticationStatus()); + self::assertNull($token->getAccount()); + } + + #[Test] + public function theChallengeIsSingleUseEvenIfVerificationFails(): void + { + $this->sessionStorage->method('getValue')->willReturn('{"stored":"options"}'); + $this->webAuthnService->method('verifyPasswordlessAssertion')->willThrowException(new \RuntimeException('bad signature')); + $this->sessionStorage->expects(self::once())->method('removeValue') + ->with(SecondFactorSessionStorageService::SESSION_OBJECT_WEBAUTHN_PASSWORDLESS_OPTIONS); + + $this->provider->authenticate($this->tokenWithAssertion('the-assertion')); + } + + #[Test] + public function rejectsWithoutAChallengeInTheSession(): void + { + $this->sessionStorage->method('getValue')->willReturn(null); + $this->webAuthnService->expects(self::never())->method('verifyPasswordlessAssertion'); + $this->securityLogger->expects(self::once())->method('warning')->with(self::stringContains('no passwordless login in progress')); + + $token = $this->tokenWithAssertion('the-assertion'); + $this->provider->authenticate($token); + + self::assertSame(TokenInterface::WRONG_CREDENTIALS, $token->getAuthenticationStatus()); + } + + #[Test] + public function rejectsWhilePasswordlessLoginIsDisabled(): void + { + $this->inject($this->provider, 'passwordlessLoginEnabled', false); + $this->sessionStorage->method('getValue')->willReturn('{"stored":"options"}'); + $this->webAuthnService->expects(self::never())->method('verifyPasswordlessAssertion'); + $this->securityLogger->expects(self::once())->method('warning')->with(self::stringContains('disabled')); + + $token = $this->tokenWithAssertion('the-assertion'); + $this->provider->authenticate($token); + + self::assertSame(TokenInterface::WRONG_CREDENTIALS, $token->getAuthenticationStatus()); + } + + #[Test] + public function tokenPicksUpTheNamespacedAssertionOfAPostRequest(): void + { + $token = $this->tokenWithAssertion('the-assertion'); + + self::assertSame(TokenInterface::AUTHENTICATION_NEEDED, $token->getAuthenticationStatus()); + self::assertSame('the-assertion', $token->getCredentials()['assertion']); + } + + #[Test] + public function tokenIgnoresAPlainAssertionArgument(): void + { + // the 2nd-factor WebAuthn endpoint posts a plain `assertion` - it must not trigger a passwordless login + $token = new WebAuthnPasswordlessToken(); + $token->updateCredentials($this->actionRequest('POST', ['assertion' => 'the-assertion'], [])); + + self::assertSame(TokenInterface::NO_CREDENTIALS_GIVEN, $token->getAuthenticationStatus()); + } + + #[Test] + public function tokenIgnoresGetRequests(): void + { + $token = new WebAuthnPasswordlessToken(); + $token->updateCredentials($this->actionRequest('GET', [], $this->namespacedAssertion('the-assertion'))); + + self::assertSame(TokenInterface::NO_CREDENTIALS_GIVEN, $token->getAuthenticationStatus()); + } + + private function tokenWithAssertion(string $assertion): WebAuthnPasswordlessToken + { + $token = new WebAuthnPasswordlessToken(); + $token->updateCredentials($this->actionRequest('POST', [], $this->namespacedAssertion($assertion))); + return $token; + } + + private function namespacedAssertion(string $assertion): array + { + return ['__authentication' => ['Sandstorm' => ['BackendUserManagement' => ['Passwordless' => ['assertion' => $assertion]]]]]; + } + + private function actionRequest(string $method, array $arguments, array $internalArguments): ActionRequest + { + $actionRequest = $this->createMock(ActionRequest::class); + $actionRequest->method('getHttpRequest')->willReturn(new ServerRequest($method, 'https://neos.example/')); + $actionRequest->method('getArguments')->willReturn($arguments); + $actionRequest->method('getInternalArguments')->willReturn($internalArguments); + return $actionRequest; + } +} diff --git a/Tests/Unit/SecondFactor/Service/WebAuthnServiceTest.php b/Tests/Unit/SecondFactor/Service/WebAuthnServiceTest.php index e3ba53c..1c29492 100644 --- a/Tests/Unit/SecondFactor/Service/WebAuthnServiceTest.php +++ b/Tests/Unit/SecondFactor/Service/WebAuthnServiceTest.php @@ -39,6 +39,7 @@ public function resolvesBackendAccountByUserHandle(): void { $account = $this->createMock(Account::class); $account->method('getAuthenticationProviderName')->willReturn('Neos.Neos:Backend'); + $account->method('isActive')->willReturn(true); $this->persistenceManager ->method('getObjectByIdentifier') ->with('the-user-handle', Account::class) @@ -47,6 +48,19 @@ public function resolvesBackendAccountByUserHandle(): void self::assertSame($account, $this->service->resolveBackendAccountByUserHandle('the-user-handle')); } + #[Test] + public function throwsWhenAccountIsInactive(): void + { + $account = $this->createMock(Account::class); + $account->method('getAuthenticationProviderName')->willReturn('Neos.Neos:Backend'); + $account->method('isActive')->willReturn(false); + $this->persistenceManager->method('getObjectByIdentifier')->willReturn($account); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionCode(1793795361); + $this->service->resolveBackendAccountByUserHandle('the-user-handle'); + } + #[Test] public function throwsWhenNoAccountExistsForUserHandle(): void { From 475c913ffcc05d091e443e96d50c50ba197b6146 Mon Sep 17 00:00:00 2001 From: Timon Heuser Date: Wed, 4 Nov 2026 13:59:10 +0100 Subject: [PATCH 2/5] SECURITY: log failed login attempts via passwordless login --- .../WebAuthnPasswordlessProvider.php | 49 ++++++++++++++++--- ...PasswordlessAssertionRejectedException.php | 21 ++++++++ .../SecondFactor/Service/WebAuthnService.php | 36 +++++++++----- .../WebAuthnPasswordlessProviderTest.php | 45 +++++++++++++++++ 4 files changed, 132 insertions(+), 19 deletions(-) create mode 100644 Classes/SecondFactor/Service/PasswordlessAssertionRejectedException.php diff --git a/Classes/SecondFactor/Security/Authentication/WebAuthnPasswordlessProvider.php b/Classes/SecondFactor/Security/Authentication/WebAuthnPasswordlessProvider.php index add51b0..a385c05 100644 --- a/Classes/SecondFactor/Security/Authentication/WebAuthnPasswordlessProvider.php +++ b/Classes/SecondFactor/Security/Authentication/WebAuthnPasswordlessProvider.php @@ -6,6 +6,9 @@ use Neos\Flow\Core\Bootstrap; use Neos\Flow\Http\HttpRequestHandlerInterface; use Neos\Flow\Http\ServerRequestAttributes; +use Neos\Flow\Persistence\PersistenceManagerInterface; +use Neos\Flow\Security\Account; +use Neos\Flow\Security\AccountRepository; use Neos\Flow\Security\Authentication\Provider\AbstractProvider; use Neos\Flow\Security\Authentication\TokenInterface; use Neos\Flow\Security\Exception\UnsupportedAuthenticationTokenException; @@ -13,6 +16,7 @@ use Psr\Log\LoggerInterface; use Sandstorm\BackendUserManagement\SecondFactor\Domain\AuthenticationStatus; use Sandstorm\BackendUserManagement\SecondFactor\Security\Token\WebAuthnPasswordlessToken; +use Sandstorm\BackendUserManagement\SecondFactor\Service\PasswordlessAssertionRejectedException; use Sandstorm\BackendUserManagement\SecondFactor\Service\SecondFactorSessionStorageService; use Sandstorm\BackendUserManagement\SecondFactor\Service\WebAuthnService; @@ -50,6 +54,18 @@ class WebAuthnPasswordlessProvider extends AbstractProvider */ protected $bootstrap; + /** + * @Flow\Inject + * @var AccountRepository + */ + protected $accountRepository; + + /** + * @Flow\Inject + * @var PersistenceManagerInterface + */ + protected $persistenceManager; + /** * @Flow\Inject(name="Neos.Flow:SecurityLogger") * @var LoggerInterface @@ -111,14 +127,22 @@ public function authenticate(TokenInterface $authenticationToken) $httpRequest ); } catch (\Throwable $exception) { + // Only a known credential of an active backend account yields an account here - like Flow's + // password provider, which counts failures only for accounts it found via findActiveBy...(). + $knownAccount = $exception instanceof PasswordlessAssertionRejectedException ? $exception->account : null; + if ($knownAccount !== null) { + $this->recordAuthenticationAttempt($knownAccount, TokenInterface::WRONG_CREDENTIALS); + } $this->rejectLogin( $authenticationToken, sprintf('%s (%s)', $exception->getMessage(), $exception->getCode()), - $httpRequest + $httpRequest, + $knownAccount ); return; } + $this->recordAuthenticationAttempt($account, TokenInterface::AUTHENTICATION_SUCCESSFUL); $authenticationToken->setAccount($account); $authenticationToken->setAuthenticationStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL); @@ -127,14 +151,27 @@ public function authenticate(TokenInterface $authenticationToken) $this->secondFactorSessionStorageService->setAuthenticationStatus(AuthenticationStatus::AUTHENTICATED); } - private function rejectLogin(WebAuthnPasswordlessToken $token, string $reason, ?ServerRequestInterface $httpRequest): void + /** + * Same as PersistedUsernamePasswordProvider: a failure increases Account::$failedAuthenticationCount, + * a success resets it and sets lastSuccessfulAuthenticationDate. + */ + private function recordAuthenticationAttempt(Account $account, int $authenticationStatus): void + { + $account->authenticationAttempted($authenticationStatus); + $this->accountRepository->update($account); + // persisted even if the request turns out to be a "safe" one + $this->persistenceManager->allowObject($account); + } + + private function rejectLogin(WebAuthnPasswordlessToken $token, string $reason, ?ServerRequestInterface $httpRequest, ?Account $account = null): void { $token->setAuthenticationStatus(TokenInterface::WRONG_CREDENTIALS); $clientIp = $httpRequest?->getAttribute(ServerRequestAttributes::CLIENT_IP); - $this->securityLogger->warning( - self::LOGGING_PREFIX . 'Passwordless passkey login failed: ' . $reason, - ['clientIp' => is_string($clientIp) ? $clientIp : 'unknown'] - ); + $context = ['clientIp' => is_string($clientIp) ? $clientIp : 'unknown']; + if ($account !== null) { + $context['accountIdentifier'] = $account->getAccountIdentifier(); + } + $this->securityLogger->warning(self::LOGGING_PREFIX . 'Passwordless passkey login failed: ' . $reason, $context); } private function currentHttpRequest(): ?ServerRequestInterface diff --git a/Classes/SecondFactor/Service/PasswordlessAssertionRejectedException.php b/Classes/SecondFactor/Service/PasswordlessAssertionRejectedException.php new file mode 100644 index 0000000..803b55c --- /dev/null +++ b/Classes/SecondFactor/Service/PasswordlessAssertionRejectedException.php @@ -0,0 +1,21 @@ +getMessage(), 1793796650, $previous); + } +} diff --git a/Classes/SecondFactor/Service/WebAuthnService.php b/Classes/SecondFactor/Service/WebAuthnService.php index 6f5f784..48f006f 100644 --- a/Classes/SecondFactor/Service/WebAuthnService.php +++ b/Classes/SecondFactor/Service/WebAuthnService.php @@ -301,12 +301,16 @@ public function createPasswordlessAuthenticationOptions(string $hostname): Publi * Verify a usernameless assertion and resolve the Neos backend account it belongs to. * * The assertion carries both the credential id and a user handle. We look the credential - * up by its id first (proving we actually stored it), then let the library verify the - * assertion against that credential's stored user handle, and finally map the user handle - * (the account's persistence identifier) back to the Flow account. Only Neos backend - * accounts may use this login path. + * up by its id first (proving we actually stored it), map its stored user handle (the + * account's persistence identifier) back to the Flow account, and only then let the library + * verify the assertion against that credential. Only active Neos backend accounts may use + * this login path. * - * @throws \Throwable when validation fails or no matching backend account exists + * The account is resolved before the signature check, so a rejected assertion can be + * counted on it ({@see PasswordlessAssertionRejectedException}). + * + * @throws PasswordlessAssertionRejectedException when the assertion of a known credential does not verify + * @throws \Throwable when the credential is unknown or no matching active backend account exists */ public function verifyPasswordlessAssertion( string $assertionResponseJson, @@ -327,21 +331,27 @@ public function verifyPasswordlessAssertion( } $userHandle = $credentialSource->userHandle; + $account = $this->resolveBackendAccountByUserHandle($userHandle); + $validator = AuthenticatorAssertionResponseValidator::create( $this->buildCeremonyStepManagerFactory()->requestCeremony() ); - $updatedCredential = $validator->check( - $credentialSource, - $authenticatorResponse, - $options, - $request->getUri()->getHost(), - $userHandle - ); + try { + $updatedCredential = $validator->check( + $credentialSource, + $authenticatorResponse, + $options, + $request->getUri()->getHost(), + $userHandle + ); + } catch (\Throwable $exception) { + throw new PasswordlessAssertionRejectedException($account, $exception); + } // Persist the bumped counter so replay protection stays effective across logins. $this->credentialSourceRepository->saveCredential($updatedCredential); - return $this->resolveBackendAccountByUserHandle($userHandle); + return $account; } /** diff --git a/Tests/Unit/SecondFactor/Security/WebAuthnPasswordlessProviderTest.php b/Tests/Unit/SecondFactor/Security/WebAuthnPasswordlessProviderTest.php index 0f2b43a..2d8a3e7 100644 --- a/Tests/Unit/SecondFactor/Security/WebAuthnPasswordlessProviderTest.php +++ b/Tests/Unit/SecondFactor/Security/WebAuthnPasswordlessProviderTest.php @@ -7,7 +7,9 @@ use Neos\Flow\Http\HttpRequestHandlerInterface; use Neos\Flow\Http\ServerRequestAttributes; use Neos\Flow\Mvc\ActionRequest; +use Neos\Flow\Persistence\PersistenceManagerInterface; use Neos\Flow\Security\Account; +use Neos\Flow\Security\AccountRepository; use Neos\Flow\Security\Authentication\AuthenticationProviderInterface; use Neos\Flow\Security\Authentication\TokenInterface; use Neos\Flow\Tests\UnitTestCase; @@ -17,6 +19,7 @@ use Sandstorm\BackendUserManagement\SecondFactor\Domain\AuthenticationStatus; use Sandstorm\BackendUserManagement\SecondFactor\Security\Authentication\WebAuthnPasswordlessProvider; use Sandstorm\BackendUserManagement\SecondFactor\Security\Token\WebAuthnPasswordlessToken; +use Sandstorm\BackendUserManagement\SecondFactor\Service\PasswordlessAssertionRejectedException; use Sandstorm\BackendUserManagement\SecondFactor\Service\SecondFactorSessionStorageService; use Sandstorm\BackendUserManagement\SecondFactor\Service\WebAuthnService; use Webauthn\PublicKeyCredentialRequestOptions; @@ -31,6 +34,8 @@ class WebAuthnPasswordlessProviderTest extends UnitTestCase private LoggerInterface&MockObject $securityLogger; + private AccountRepository&MockObject $accountRepository; + private ServerRequest $httpRequest; protected function setUp(): void @@ -55,6 +60,9 @@ protected function setUp(): void $this->inject($this->provider, 'secondFactorSessionStorageService', $this->sessionStorage); $this->inject($this->provider, 'bootstrap', $bootstrap); $this->inject($this->provider, 'securityLogger', $this->securityLogger); + $this->accountRepository = $this->createMock(AccountRepository::class); + $this->inject($this->provider, 'accountRepository', $this->accountRepository); + $this->inject($this->provider, 'persistenceManager', $this->createMock(PersistenceManagerInterface::class)); $this->inject($this->provider, 'passwordlessLoginEnabled', true); } @@ -62,6 +70,9 @@ protected function setUp(): void public function authenticatesTheAccountOfAValidAssertion(): void { $account = $this->createMock(Account::class); + // resets the failed-attempt counter, like Flow's password provider + $account->expects(self::once())->method('authenticationAttempted')->with(TokenInterface::AUTHENTICATION_SUCCESSFUL); + $this->accountRepository->expects(self::once())->method('update')->with($account); $this->sessionStorage->method('getValue')->willReturn('{"stored":"options"}'); $this->webAuthnService->expects(self::once())->method('verifyPasswordlessAssertion') ->with('the-assertion', self::anything(), $this->httpRequest) @@ -95,6 +106,40 @@ public function rejectsAndLogsAFailedVerification(): void self::assertNull($token->getAccount()); } + #[Test] + public function countsARejectedAssertionOnTheKnownAccount(): void + { + $account = $this->createMock(Account::class); + $account->method('getAccountIdentifier')->willReturn('editor'); + $account->expects(self::once())->method('authenticationAttempted')->with(TokenInterface::WRONG_CREDENTIALS); + $this->accountRepository->expects(self::once())->method('update')->with($account); + $this->sessionStorage->method('getValue')->willReturn('{"stored":"options"}'); + $this->webAuthnService->method('verifyPasswordlessAssertion') + ->willThrowException(new PasswordlessAssertionRejectedException($account, new \RuntimeException('bad signature'))); + $this->securityLogger->expects(self::once())->method('warning')->with( + self::stringContains('bad signature'), + ['clientIp' => '203.0.113.7', 'accountIdentifier' => 'editor'] + ); + + $token = $this->tokenWithAssertion('the-assertion'); + $this->provider->authenticate($token); + + self::assertSame(TokenInterface::WRONG_CREDENTIALS, $token->getAuthenticationStatus()); + self::assertNull($token->getAccount()); + } + + #[Test] + public function countsNothingWithoutAKnownAccount(): void + { + // unknown credential, inactive or non-backend account: nothing to count on (Flow counts only active accounts) + $this->sessionStorage->method('getValue')->willReturn('{"stored":"options"}'); + $this->webAuthnService->method('verifyPasswordlessAssertion') + ->willThrowException(new \RuntimeException('Unknown passkey credential', 1751200001)); + $this->accountRepository->expects(self::never())->method('update'); + + $this->provider->authenticate($this->tokenWithAssertion('the-assertion')); + } + #[Test] public function theChallengeIsSingleUseEvenIfVerificationFails(): void { From ad0daf4779a22e3e3c6aa86f05622969174d33c9 Mon Sep 17 00:00:00 2001 From: Timon Heuser Date: Wed, 4 Nov 2026 14:10:05 +0100 Subject: [PATCH 3/5] SECURITY: escape 2nd factor names on output --- .../Integration/Controller/Module/NewTotp.fusion | 2 +- .../Integration/Controller/Module/NewWebAuthn.fusion | 2 +- .../Presentation/Components/SecondFactorList.fusion | 6 ++++-- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/Resources/Private/Fusion/SecondFactor/Integration/Controller/Module/NewTotp.fusion b/Resources/Private/Fusion/SecondFactor/Integration/Controller/Module/NewTotp.fusion index ef1bdc1..19ec7cd 100644 --- a/Resources/Private/Fusion/SecondFactor/Integration/Controller/Module/NewTotp.fusion +++ b/Resources/Private/Fusion/SecondFactor/Integration/Controller/Module/NewTotp.fusion @@ -10,7 +10,7 @@ Sandstorm.BackendUserManagement.SecondFactor.ModuleController.newTotp = Sandstor

- {I18n.id('module.new.user-context').package('Sandstorm.BackendUserManagement').source('SecondFactor').arguments([currentUser ? currentUser.name.fullName : accountIdentifier]).translate()} + {I18n.id('module.new.user-context').package('Sandstorm.BackendUserManagement').source('SecondFactor').arguments([String.htmlSpecialChars(currentUser ? currentUser.name.fullName : accountIdentifier)]).translate()}

1 diff --git a/Resources/Private/Fusion/SecondFactor/Integration/Controller/Module/NewWebAuthn.fusion b/Resources/Private/Fusion/SecondFactor/Integration/Controller/Module/NewWebAuthn.fusion index fc4981b..bd1c0a9 100644 --- a/Resources/Private/Fusion/SecondFactor/Integration/Controller/Module/NewWebAuthn.fusion +++ b/Resources/Private/Fusion/SecondFactor/Integration/Controller/Module/NewWebAuthn.fusion @@ -16,7 +16,7 @@ Sandstorm.BackendUserManagement.SecondFactor.ModuleController.newWebAuthn = Sand } renderer = afx`

- {I18n.id('module.new.user-context').package('Sandstorm.BackendUserManagement').source('SecondFactor').arguments([currentUser ? currentUser.name.fullName : accountIdentifier]).translate()} + {I18n.id('module.new.user-context').package('Sandstorm.BackendUserManagement').source('SecondFactor').arguments([String.htmlSpecialChars(currentUser ? currentUser.name.fullName : accountIdentifier)]).translate()}

- {props.factorAndPerson.user.name.fullName} ({props.factorAndPerson.secondFactor.account.accountIdentifier}) + {String.htmlSpecialChars(props.factorAndPerson.user.name.fullName)} ({String.htmlSpecialChars(props.factorAndPerson.secondFactor.account.accountIdentifier)}) {props.factorAndPerson.secondFactor.typeAsName} - {props.factorAndPerson.secondFactor.name == null ? '-' : props.factorAndPerson.secondFactor.name} + {props.factorAndPerson.secondFactor.name == null ? '-' : String.htmlSpecialChars(props.factorAndPerson.secondFactor.name)} {props.factorAndPerson.secondFactor.creationDate == null ? '-' : Date.format(props.factorAndPerson.secondFactor.creationDate, 'Y-m-d H:i')}