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
33 changes: 33 additions & 0 deletions app/libs/Auth/AuthService.php
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,39 @@ public function login(string $username, string $password, bool $remember_me): bo
return true;
}

/**
* @param string $username
* @param string $password
* @return User|null
* @throws AuthenticationException
*/
public function validateCredentials(string $username, string $password): User
{
Log::debug("AuthService::validateCredentials");

/**
* @var User|null $user
*/
$user = Auth::getProvider()->retrieveByCredentials(['username' => $username, 'password' => $password]);
if (!$user) {
throw new AuthenticationException();
}

return $user;
}

/**
* @param User $user
* @param bool $remember
* @return void
*/
public function loginUser(User $user, bool $remember): void
{
Log::debug("AuthService::loginUser");
if (!$user->canLogin()) throw new AuthenticationException("User is not active or cannot login.");
Auth::login($user, $remember);
Comment thread
matiasperrone-exo marked this conversation as resolved.
}

/**
* @param OAuth2OTP $otpClaim
* @param Client|null $client
Expand Down
22 changes: 22 additions & 0 deletions app/libs/Utils/Services/IAuthService.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,28 @@ public function getCurrentUser():?User;
*/
public function login(string $username, string $password, bool $remember_me): bool;

/**
* Validates the supplied credentials without establishing a session.
* Delegates to CustomAuthProvider::retrieveByCredentials() so security
* checkpoints (LockUserCounterMeasure, etc.) still fire on failure.
*
* @param string $username
* @param string $password
* @return User
* @throws AuthenticationException on invalid credentials, missing user, or locked account.
*/
public function validateCredentials(string $username, string $password): User;

/**
* Establishes a Laravel session for an already-authenticated user.
* Used by the 2FA flow after the second factor is verified.
*
* @param User $user
* @param bool $remember
* @return void
*/
public function loginUser(User $user, bool $remember): void;

/**
* @param OAuth2OTP $otpClaim
* @param Client|null $client
Expand Down
106 changes: 106 additions & 0 deletions tests/AuthServiceValidateCredentialsIntegrationTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<?php namespace Tests;
/**
* Copyright 2026 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/

use Auth\Exceptions\AuthenticationException;
use Auth\Repositories\IUserRepository;
use Auth\User;
use Illuminate\Support\Facades\Auth;
use LaravelDoctrine\ORM\Facades\EntityManager;
use Utils\Services\IAuthService;
use Utils\Services\UtilsServiceCatalog;

/**
* Class AuthServiceValidateCredentialsIntegrationTest
* Exercises AuthService::validateCredentials() against the real database and
* security-checkpoint stack to verify that failed attempts increment the
* user's login_failed_attempt counter (via LockUserCounterMeasure) and that
* no session is established on either success or failure.
*/
final class AuthServiceValidateCredentialsIntegrationTest extends OpenStackIDBaseTestCase
{
// CustomAuthProvider looks up users via IUserRepository::getByEmailOrName(),
// which currently matches only on the email column — so login uses the email
// as the "username".
private const SEEDED_USERNAME = 'sebastian@tipit.net';
private const SEEDED_PASSWORD = '1Qaz2wsx!';

private IAuthService $auth_service;

protected function prepareForTests(): void
{
parent::prepareForTests();
$this->auth_service = $this->app[UtilsServiceCatalog::AuthenticationService];
}

/**
* A failed validateCredentials() call must:
* - throw AuthenticationException,
* - NOT establish a session (Auth::check() stays false),
* - trigger LockUserCounterMeasure so the user's login_failed_attempt counter increments.
*/
public function testFailedAttempt_incrementsLoginFailedAttemptCounter(): void
{
$initial_attempts = $this->getLoginFailedAttempt(self::SEEDED_USERNAME);
$this->assertFalse(Auth::check(), 'precondition: no authenticated user');

$threw = false;
try {
$this->auth_service->validateCredentials(self::SEEDED_USERNAME, 'wrong-password');
} catch (AuthenticationException $ex) {
$threw = true;
}

$this->assertTrue($threw, 'Expected AuthenticationException on wrong password');
$this->assertFalse(Auth::check(), 'No session should be established after a failed attempt');

$new_attempts = $this->getLoginFailedAttempt(self::SEEDED_USERNAME);
$this->assertSame(
$initial_attempts + 1,
$new_attempts,
'login_failed_attempt counter must increment via LockUserCounterMeasure'
);
}

/**
* A successful validateCredentials() call must return the user without
* establishing a session — Auth::check() must remain false afterwards.
*/
public function testSuccessfulValidation_doesNotEstablishSession(): void
{
$this->assertFalse(Auth::check(), 'precondition: no authenticated user');

$user = $this->auth_service->validateCredentials(
self::SEEDED_USERNAME,
self::SEEDED_PASSWORD
);

$this->assertInstanceOf(User::class, $user);
$this->assertFalse(
Auth::check(),
'validateCredentials() must NOT call Auth::login() on success'
);
}

private function getLoginFailedAttempt(string $username): int
{
// Clear Doctrine's identity map so we read fresh state from the DB,
// not a cached in-memory entity from a prior transaction.
EntityManager::clear();
$repo = EntityManager::getRepository(User::class);
/** @var IUserRepository $repo */
$user = $repo->getByEmailOrName($username);
$this->assertInstanceOf(User::class, $user, "Seeded user {$username} not found");
return $user->getLoginFailedAttempt();
}
}
182 changes: 182 additions & 0 deletions tests/unit/AuthServiceValidateCredentialsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
<?php namespace Tests;
/**
* Copyright 2026 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/

use App\libs\OAuth2\Repositories\IOAuth2OTPRepository;
use Auth\AuthService;
use Auth\CustomAuthProvider;
use Auth\Exceptions\AuthenticationException;
use Auth\Repositories\IUserRepository;
use Mockery;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use OAuth2\Services\IPrincipalService;
use OAuth2\Services\ISecurityContextService;
use OpenId\Services\IUserService;
use App\Services\Auth\IUserService as IAuthUserService;
use PHPUnit\Framework\TestCase as PHPUnitTestCase;
use Services\IUserActionService;
use Utils\Db\ITransactionService;
use Utils\Services\ICacheService;

/**
* Class AuthServiceValidateCredentialsTest
* Verifies that AuthService::validateCredentials() validates the password
* WITHOUT establishing a session, and that AuthService::loginUser() calls
* Auth::login() for the 2FA completion step.
*/
#[\PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses]
#[\PHPUnit\Framework\Attributes\PreserveGlobalState(false)]
final class AuthServiceValidateCredentialsTest extends PHPUnitTestCase
{
use MockeryPHPUnitIntegration;

private AuthService $service;

private $mock_user_repository;

// Facade aliases
private $auth_mock;
private $log_mock;

protected function setUp(): void
{
parent::setUp();

$this->mock_user_repository = $this->createMock(IUserRepository::class);
$mock_otp_repository = $this->createMock(IOAuth2OTPRepository::class);
$mock_principal_service = $this->createMock(IPrincipalService::class);
$mock_user_service = $this->createMock(IUserService::class);
$mock_user_action_service = $this->createMock(IUserActionService::class);
$mock_cache_service = $this->createMock(ICacheService::class);
$mock_auth_user_service = $this->createMock(IAuthUserService::class);
$mock_security_context_service = $this->createMock(ISecurityContextService::class);
$mock_tx_service = $this->createMock(ITransactionService::class);

$this->auth_mock = Mockery::mock('alias:Illuminate\Support\Facades\Auth');
$this->log_mock = Mockery::mock('alias:Illuminate\Support\Facades\Log');

$this->log_mock->shouldReceive('debug')->zeroOrMoreTimes();
$this->log_mock->shouldReceive('warning')->zeroOrMoreTimes();

$this->service = new AuthService(
$this->mock_user_repository,
$mock_otp_repository,
$mock_principal_service,
$mock_user_service,
$mock_user_action_service,
$mock_cache_service,
$mock_auth_user_service,
$mock_security_context_service,
$mock_tx_service
);
}

/**
* Valid credentials return the User WITHOUT establishing a session.
* Auth::login() and Auth::attempt() must NEVER be called.
*/
public function testValidCredentials_returnsUser_withoutEstablishingSession(): void
{
$username = 'jane.doe';
$password = 'Str0ng!Pass';

$resolved_user = Mockery::mock('Auth\User');

$provider_mock = Mockery::mock(CustomAuthProvider::class);
$provider_mock->shouldReceive('retrieveByCredentials')
->once()
->with(['username' => $username, 'password' => $password])
->andReturn($resolved_user);

$this->auth_mock->shouldReceive('getProvider')->once()->andReturn($provider_mock);
$this->auth_mock->shouldNotReceive('login');
$this->auth_mock->shouldNotReceive('attempt');

$returned = $this->service->validateCredentials($username, $password);

$this->assertSame($resolved_user, $returned);
}

/**
* Invalid credentials (provider returns null) throw AuthenticationException
* and do NOT establish a session.
*/
public function testInvalidCredentials_throwsAuthenticationException(): void
{
$username = 'jane.doe';
$password = 'wrong';

$provider_mock = Mockery::mock(CustomAuthProvider::class);
$provider_mock->shouldReceive('retrieveByCredentials')
->once()
->with(['username' => $username, 'password' => $password])
->andReturn(null);

$this->auth_mock->shouldReceive('getProvider')->once()->andReturn($provider_mock);
$this->auth_mock->shouldNotReceive('login');
$this->auth_mock->shouldNotReceive('attempt');

$this->expectException(AuthenticationException::class);

$this->service->validateCredentials($username, $password);
}

/**
* loginUser(user, true) delegates to Auth::login with the remember flag set.
*/
public function testLoginUser_callsAuthLogin_withRememberTrue(): void
{
$user = Mockery::mock('Auth\User');
$user->shouldReceive('canLogin')->andReturn(true);

$this->auth_mock
->shouldReceive('login')
->once()
->with($user, true);

$this->service->loginUser($user, true);
}

/**
* loginUser(user, false) delegates to Auth::login with remember disabled.
*/
public function testLoginUser_callsAuthLogin_withRememberFalse(): void
{
$user = Mockery::mock('Auth\User');
$user->shouldReceive('canLogin')->andReturn(true);

$this->auth_mock
->shouldReceive('login')
->once()
->with($user, false);

$this->service->loginUser($user, false);
}

/**
* loginUser(user, [true|false]) and isActive or canLogin false throws an Exception.
*/
public function testLoginUser_throwsException_whenIsNotActive(): void
{
$user = Mockery::mock('Auth\User');
$user->shouldReceive('canLogin')->andReturn(false);

$this->auth_mock->shouldNotReceive('login');

$this->expectException(AuthenticationException::class);
$this->expectExceptionMessageMatches('/User is not active or cannot login\./');

$this->service->loginUser($user, true);
}

}
Loading