Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ The format is based on Keep a Changelog.
- The `Exception` of a failed Dropbox or Google Drive request carries a plain text error body as it is, and the HTTP client's error when the response has no body; a text body was JSON encoded, and an error body that was plain text raised a `TypeError` in the check for an expired access token (#694)
- `config()->set()` with a dotted key on an empty config, such as `set('cache.redis', [...])`, nests the value as it does on a config that has values; it stored the literal key `cache.redis`, so `get('cache.redis.port')` returned `null` (#672)
- `Environment::updateRow()` finds the line of the key as the `.env` file has it: a quoted value (`APP_NAME="My App"`, `APP_NAME='My App'`, and a double-quoted value over several lines), an empty one (`APP_NAME=""`) and a `KEY` line without `=` are replaced now; they were left unchanged in the file, and `APP_NAME=""` became `APP_NAME=new""`. A comment after the value stays. The value is written as it is given: a `$` or `\` in it, such as `$1` or `\0`, was read by `preg_replace()` as a reference to the match and changed the written value. A line that cannot be found as it was read, such as `export KEY=value` or a value with `\"` in it, is still left unchanged. When the replacement fails, `updateRow()` throws `EnvException::fileNotFound()`, as it does when the file cannot be read, and keeps the file; it wrote an empty `.env` (#709)
- **Security:** with two-factor authentication on, `SessionAuthAdapter` issues the remember-me token and cookie only after `verifyOtp()` accepts the OTP, in the browser that asked for "remember me". `signin()` issued them before the OTP step, so a remember cookie from a sign-in whose OTP was never entered signed the browser in once the owner completed an OTP sign-in elsewhere, and a failure while storing the OTP left a working remember token. With two-factor authentication off, nothing changes. Remember tokens issued before the upgrade are not revoked; clear the remember token field of your users to sign remembered browsers out (#707)
- **Security:** `SessionAuthAdapter::verifyOtp()` gives the session a new ID before it signs the user in, as `signin()` does without two-factor authentication. It kept the ID the browser had before the sign-in, so a session ID planted in the browser before a two-factor sign-in stayed valid for the signed-in user (#707)
- **Security:** a sign-in through the remember-me cookie (`SessionAuthAdapter::user()`) also gives the session a new ID before it signs the user in. It kept the ID the browser had, so a session ID planted in the browser of a remembered user stayed valid for that user once the cookie signed them in (#707)

## [3.1.2] - 2026-11-19

Expand Down
30 changes: 26 additions & 4 deletions src/Auth/Adapters/SessionAuthAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ class SessionAuthAdapter implements AuthenticatableInterface

private const DEFAULT_REMEMBER_LIFETIME = 2592000;

/**
* Session key that remembers, until the OTP is verified, which user asked for "remember me"
*/
private const AUTH_REMEMBER = 'auth_remember';

private int $rememberLifetime;

/**
Expand Down Expand Up @@ -77,14 +82,20 @@ public function signin(string $username, string $password, bool $remember = fals
{
$user = $this->getUser($username, $password);

if ($remember) {
$this->setRememberToken($user);
}

if ($this->isTwoFactorEnabled()) {
if ($remember) {
session()->set(self::AUTH_REMEMBER, $user->getFieldValue($this->keyFields[AuthKeys::USERNAME->value]));
} else {
session()->delete(self::AUTH_REMEMBER);
}

return $this->twoStepVerification($user);
}

if ($remember) {
$this->setRememberToken($user);
}

session()->regenerateId();
session()->set(self::AUTH_USER, $this->getVisibleFields($user));

Expand All @@ -100,6 +111,8 @@ public function signin(string $username, string $password, bool $remember = fals
*/
public function signout(): bool
{
session()->delete(self::AUTH_REMEMBER);

if (session()->has(self::AUTH_USER)) {
session()->delete(self::AUTH_USER);
session()->regenerateId();
Expand Down Expand Up @@ -128,6 +141,7 @@ public function user(): ?User
$user = $this->checkRememberToken();

if ($user) {
session()->regenerateId();
session()->set(self::AUTH_USER, $this->getVisibleFields($user));
return $this->user();
}
Expand Down Expand Up @@ -171,6 +185,14 @@ public function verifyOtp(int $otp, string $otpToken): bool
{
$user = $this->verifyAndUpdateOtp($otp, $otpToken);

$rememberFor = session()->get(self::AUTH_REMEMBER);
session()->delete(self::AUTH_REMEMBER);

if ($rememberFor !== null && $rememberFor === $user->getFieldValue($this->keyFields[AuthKeys::USERNAME->value])) {
$this->setRememberToken($user);
}

session()->regenerateId();
session()->set(self::AUTH_USER, $this->getVisibleFields($user));

return true;
Expand Down
251 changes: 251 additions & 0 deletions tests/Unit/Auth/Adapters/SessionAuthAdapterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@
use Quantum\Tests\Unit\Auth\AuthTestCase;
use Quantum\Auth\Adapters\JwtAuthAdapter;
use Quantum\Auth\Traits\AuthTrait;
use Quantum\Mailer\Mailer;
use Quantum\Hasher\Hasher;
use ArgumentCountError;
use Quantum\Auth\User;
use ReflectionMethod;
use RuntimeException;
use Mockery;

class SessionAuthAdapterTest extends AuthTestCase
Expand Down Expand Up @@ -43,12 +45,72 @@ private function createSessionAuth(): SessionAuthAdapter
);
}

private function enableTwoFactor(): void
{
config()->set('auth.two_fa', true);
config()->set('auth.otp_expires', 2);
$this->sessionAuth = $this->createSessionAuth();
}

private function createSessionAuthWith(AuthServiceInterface $authService, Mailer $mailer): SessionAuthAdapter
{
return new SessionAuthAdapter($authService, $mailer, (new Hasher())->setCost(4), config()->section('auth'));
}

/**
* An auth service that throws when an update sets the given field to a non-empty value
*/
private function authServiceFailingOn(string $field): AuthServiceInterface
{
$authService = Mockery::mock(AuthServiceInterface::class);
$authService->shouldReceive('userSchema')->andReturn($this->userSchema);
$authService->shouldReceive('get')->andReturnUsing(fn (...$args) => $this->authService->get(...$args));
$authService->shouldReceive('update')->andReturnUsing(function (string $key, string $value, array $data) use ($field) {
if (!empty($data[$field])) {
throw new RuntimeException('The database is down');
}

return $this->authService->update($key, $value, $data);
});

return $authService;
}

/**
* A mailer whose send() throws while $fails is true
*/
private function mailerFailingWhen(bool &$fails): Mailer
{
$mailer = Mockery::mock(Mailer::class);

foreach (['setFrom', 'setAddress', 'setSubject', 'setBody', 'setTemplate'] as $method) {
$mailer->shouldReceive($method)->andReturn($mailer);
}

$mailer->shouldReceive('send')->andReturnUsing(function () use (&$fails) {
if ($fails) {
throw new RuntimeException('The mail server is down');
}

return true;
});

return $mailer;
}

private function storedRememberToken(): string
{
return (string) $this->authService->get('email', '[email protected]')->getFieldValue('remember_token');
}

public function tearDown(): void
{
self::$users = [];

$this->sessionAuth->signout();

session()->delete('cart');

parent::tearDown();
}

Expand Down Expand Up @@ -214,6 +276,195 @@ public function testWebVerifyOtp(): void
$this->assertTrue($this->sessionAuth->verifyOtp(123456789, $otp_token));
}

public function testWebSigninWithRememberAndVerificationSetsNoRememberCookieBeforeTheOtp(): void
{
$this->enableTwoFactor();

$this->sessionAuth->signin('[email protected]', 'qwerty', true);

$this->assertFalse(cookie()->has('remember_token'));
$this->assertSame('', $this->storedRememberToken());
}

public function testWebRememberCookieOfAnUnverifiedSigninDoesNotSignInAfterTheOwnerVerifiesElsewhere(): void
{
$this->enableTwoFactor();

$this->sessionAuth->signin('[email protected]', 'qwerty', true);
$firstBrowserCookie = cookie()->has('remember_token') ? cookie()->get('remember_token') : null;

cookie()->delete('remember_token');
session()->flush();

$otpToken = $this->sessionAuth->signin('[email protected]', 'qwerty');
$this->sessionAuth->verifyOtp(123456789, $otpToken);

session()->flush();
cookie()->delete('remember_token');

if ($firstBrowserCookie !== null) {
cookie()->set('remember_token', $firstBrowserCookie);
}

$this->assertNull($this->sessionAuth->user());
$this->assertSame('', $this->storedRememberToken());
}

public function testWebSigninWithRememberLeavesNoRememberTokenWhenTheOtpCannotBeStored(): void
{
$this->enableTwoFactor();

$sessionAuth = $this->createSessionAuthWith($this->authServiceFailingOn('otp'), $this->mailer);

try {
$sessionAuth->signin('[email protected]', 'qwerty', true);
$this->fail('The OTP setup did not fail');
} catch (RuntimeException $e) {
$this->assertSame('The database is down', $e->getMessage());
}

$this->assertFalse(cookie()->has('remember_token'));
$this->assertSame('', $this->storedRememberToken());
}

public function testWebVerifyOtpSetsTheRememberCookieWhenRememberWasAsked(): void
{
$this->enableTwoFactor();

$otpToken = $this->sessionAuth->signin('[email protected]', 'qwerty', true);
$this->sessionAuth->verifyOtp(123456789, $otpToken);

$this->assertTrue(cookie()->has('remember_token'));
$this->assertSame(cookie()->get('remember_token'), $this->storedRememberToken());

session()->delete('auth_user');

$this->assertTrue($this->sessionAuth->check());
}

public function testWebVerifyOtpAfterResendSetsTheRememberCookieWhenRememberWasAsked(): void
{
$this->enableTwoFactor();

$otpToken = $this->sessionAuth->signin('[email protected]', 'qwerty', true);
$otpToken = $this->sessionAuth->resendOtp($otpToken);
$this->sessionAuth->verifyOtp(123456789, $otpToken);

$this->assertTrue(cookie()->has('remember_token'));
$this->assertSame(cookie()->get('remember_token'), $this->storedRememberToken());
}

public function testWebSigninWithoutRememberForgetsAnEarlierRememberRequestWhenTheOtpMailFails(): void
{
$this->enableTwoFactor();

$this->sessionAuth->signin('[email protected]', 'qwerty', true);

$mailFails = true;
$sessionAuth = $this->createSessionAuthWith($this->authService, $this->mailerFailingWhen($mailFails));

try {
$sessionAuth->signin('[email protected]', 'qwerty');
$this->fail('The OTP mail did not fail');
} catch (RuntimeException $e) {
$this->assertSame('The mail server is down', $e->getMessage());
}

$mailFails = false;
$otpToken = $sessionAuth->resendOtp($this->authService->get('email', '[email protected]')->getFieldValue('otp_token'));
$sessionAuth->verifyOtp(123456789, $otpToken);

$this->assertFalse(cookie()->has('remember_token'));
$this->assertSame('', $this->storedRememberToken());
}

public function testWebSignoutForgetsARememberRequestWaitingForTheOtp(): void
{
$this->enableTwoFactor();

$otpToken = $this->sessionAuth->signin('[email protected]', 'qwerty', true);
$this->sessionAuth->signout();
$this->sessionAuth->verifyOtp(123456789, $otpToken);

$this->assertFalse(cookie()->has('remember_token'));
$this->assertSame('', $this->storedRememberToken());
}

public function testWebVerifyOtpForgetsTheRememberRequestWhenTheRememberTokenCannotBeStored(): void
{
$this->enableTwoFactor();

$sessionAuth = $this->createSessionAuthWith($this->authServiceFailingOn('remember_token'), $this->mailer);
$otpToken = $sessionAuth->signin('[email protected]', 'qwerty', true);

try {
$sessionAuth->verifyOtp(123456789, $otpToken);
$this->fail('Storing the remember token did not fail');
} catch (RuntimeException $e) {
$this->assertSame('The database is down', $e->getMessage());
}

$this->assertFalse(session()->has('auth_remember'));
$this->assertNull($sessionAuth->user());
}

public function testWebVerifyOtpSetsNoRememberCookieWhenRememberWasNotAsked(): void
{
$this->enableTwoFactor();

$otpToken = $this->sessionAuth->signin('[email protected]', 'qwerty');
$this->sessionAuth->verifyOtp(123456789, $otpToken);

$this->assertFalse(cookie()->has('remember_token'));
$this->assertSame('', $this->storedRememberToken());
}

public function testWebSigninWithoutRememberForgetsAnEarlierRememberRequest(): void
{
$this->enableTwoFactor();

$this->sessionAuth->signin('[email protected]', 'qwerty', true);
$otpToken = $this->sessionAuth->signin('[email protected]', 'qwerty');
$this->sessionAuth->verifyOtp(123456789, $otpToken);

$this->assertFalse(cookie()->has('remember_token'));
$this->assertSame('', $this->storedRememberToken());
}

public function testWebVerifyOtpGivesTheSessionANewId(): void
{
$this->enableTwoFactor();

$otpToken = $this->sessionAuth->signin('[email protected]', 'qwerty');

session()->set('cart', 'kept');
$sessionIdBeforeOtp = session()->getId();

$this->sessionAuth->verifyOtp(123456789, $otpToken);

$this->assertNotSame($sessionIdBeforeOtp, session()->getId());
$this->assertTrue($this->sessionAuth->check());
$this->assertSame('kept', session()->get('cart'));
}

public function testWebSigninThroughTheRememberCookieGivesTheSessionANewId(): void
{
$this->sessionAuth->signin('[email protected]', 'qwerty', true);

session()->delete('auth_user');
session()->set('cart', 'kept');
$sessionIdBeforeCookie = session()->getId();

$this->assertNotNull($this->sessionAuth->user());
$this->assertNotSame($sessionIdBeforeCookie, session()->getId());
$this->assertSame('kept', session()->get('cart'));

$sessionIdAfterCookie = session()->getId();
$this->sessionAuth->user();

$this->assertSame($sessionIdAfterCookie, session()->getId());
}

public function testWebSigninWithoutVerification(): void
{
config()->set('auth.two_fa', false);
Expand Down
Loading