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
20 changes: 14 additions & 6 deletions app/Providers/EventServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
use App\Services\Auth\IUserService;
use Auth\Repositories\IUserRepository;
use Auth\User;
use Utils\Db\ITransactionService;
use Illuminate\Database\Events\MigrationsEnded;
use Illuminate\Database\Events\MigrationsStarted;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
Expand Down Expand Up @@ -127,12 +128,19 @@ public function boot()

Event::listen(UserSpamStateUpdated::class, function($event)
{
$repository = App::make(IUserRepository::class);
$user = $repository->getById($event->getUserId());
if(is_null($user)) return;
if(! $user instanceof User) return;
$user_service = App::make(IUserService::class);
$user_service->recalculateUserSpamType($user);
// this event is also fired from User::preUpdate, while the entity manager is flushing.
// The re-classification opens a transaction (and flushes) of its own, doing that in the middle
// of a flush wipes the pending change sets of the outer one, so it must wait until the
// active transaction (if any) is committed.
$tx_service = App::make(ITransactionService::class);
$tx_service->afterCommit(function() use ($event) {
$repository = App::make(IUserRepository::class);
$user = $repository->getById($event->getUserId());
if(is_null($user)) return;
if(! $user instanceof User) return;
$user_service = App::make(IUserService::class);
$user_service->recalculateUserSpamType($user);
});
});

Event::listen(UserEmailUpdated::class, function($event)
Expand Down
16 changes: 14 additions & 2 deletions app/Services/OpenId/UserService.php
Original file line number Diff line number Diff line change
Expand Up @@ -295,8 +295,9 @@ public function create(array $payload): IEntity
public function update(int $id, array $payload): IEntity
{
$password_changed = false;
$email_changed = false;

$user = $this->tx_service->transaction(function () use ($id, $payload, &$password_changed) {
$user = $this->tx_service->transaction(function () use ($id, $payload, &$password_changed, &$email_changed) {

$user = $this->repository->getById($id);

Expand Down Expand Up @@ -371,7 +372,7 @@ public function update(int $id, array $payload): IEntity
if ($former_email != $user->getEmail()) {
Log::warning(sprintf("UserService::update use id %s - email changed old %s - email new %s", $id, $former_email, $user->getEmail()));
$user->clearEmailVerification();
Event::dispatch(new UserEmailUpdated($user->getId()));
$email_changed = true;
}

if ($former_password != $user->getPassword()) {
Expand All @@ -382,6 +383,17 @@ public function update(int $id, array $payload): IEntity
return $user;
});

// the verification token and the email are generated once the new email is stored
if ($email_changed) {
// the email change is already committed, a failure queuing the verification email must not
// skip the password change effects below
try {
Event::dispatch(new UserEmailUpdated($user->getId()));
} catch (\Exception $ex) {
Log::warning($ex);
}
}

if ($password_changed) {
Session::regenerate();
Event::dispatch(new UserPasswordResetSuccessful($user->getId()));
Expand Down
50 changes: 49 additions & 1 deletion app/Services/Utils/DoctrineTransactionService.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ final class DoctrineTransactionService implements ITransactionService

const MaxRetries = 10;

/**
* Closures registered through afterCommit while a transaction is active,
* they run once the outermost transaction is committed.
* @var Closure[]
*/
private $after_commit_callbacks = [];

/**
* DoctrineTransactionService constructor.
* @param string $manager_name
Expand Down Expand Up @@ -151,7 +158,8 @@ public function transaction(Closure $callback, int $isolationLevel = Transactio
$done = true;
}
catch (Exception $ex) {

// the work of this attempt is discarded, so are its post commit actions
$this->after_commit_callbacks = [];
$retry++;
$em->getConnection()->close();
$em->close();
Expand Down Expand Up @@ -182,6 +190,46 @@ public function transaction(Closure $callback, int $isolationLevel = Transactio
}
}

$this->runAfterCommitCallbacks();

return $result;
}

/**
* @inheritDoc
*/
public function afterCommit(Closure $callback): void
{
$em = Registry::getManager($this->manager_name);
if ($em->isOpen() && $em->getConnection()->isTransactionActive()) {
$this->after_commit_callbacks[] = $callback;
return;
}
$callback();
}

/**
* Runs the pending post commit actions, only when the outermost transaction is over.
* The data is already committed at this point, so a failure here is logged and does not
* fail (nor retry) the transaction that produced it.
*/
private function runAfterCommitCallbacks(): void
{
$em = Registry::getManager($this->manager_name);
if ($em->isOpen() && $em->getConnection()->isTransactionActive()) return;

while (count($this->after_commit_callbacks) > 0) {
// detach the committed batch first: a callback that runs a transaction of its own and fails
// clears the shared queue, that must not discard the callbacks of this batch that are still pending
$batch = $this->after_commit_callbacks;
$this->after_commit_callbacks = [];
foreach ($batch as $callback) {
try {
$callback();
} catch (\Throwable $ex) {
Log::error($ex);
}
}
}
}
}
9 changes: 9 additions & 0 deletions app/libs/Utils/Db/ITransactionService.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,13 @@ interface ITransactionService {
* @throws Exception
*/
public function transaction(Closure $callback);

/**
* Runs a Closure once the outermost active transaction has been committed.
* If there is no active transaction the Closure runs immediately.
* If the transaction is rolled back the Closure is discarded.
* @param Closure $callback
* @return void
*/
public function afterCommit(Closure $callback): void;
}
88 changes: 88 additions & 0 deletions tests/DoctrineTransactionAfterCommitTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?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 Utils\Db\ITransactionService;

/**
* Class DoctrineTransactionAfterCommitTest
* @package Tests
*/
final class DoctrineTransactionAfterCommitTest extends OpenStackIDBaseTestCase
{
private function txService(): ITransactionService
{
return $this->app->make(ITransactionService::class);
}

public function testRunsImmediatelyWhenNoTransactionIsActive(): void
{
$ran = false;
$this->txService()->afterCommit(function () use (&$ran) { $ran = true; });
$this->assertTrue($ran);
}

public function testRunsAfterTheOutermostTransactionCommits(): void
{
$tx = $this->txService();
$events = [];

$tx->transaction(function () use ($tx, &$events) {
$tx->afterCommit(function () use (&$events) { $events[] = 'callback'; });
$tx->transaction(function () use (&$events) { $events[] = 'inner'; });
$events[] = 'outer';
});

$this->assertEquals(['inner', 'outer', 'callback'], $events);
}

public function testIsDiscardedWhenTheTransactionFails(): void
{
$tx = $this->txService();
$ran = false;

try {
$tx->transaction(function () use ($tx, &$ran) {
$tx->afterCommit(function () use (&$ran) { $ran = true; });
throw new \RuntimeException('boom');
});
$this->fail('the exception must be rethrown');
} catch (\RuntimeException $ex) {
$this->assertEquals('boom', $ex->getMessage());
}

$this->assertFalse($ran);
}

/**
* A callback that runs a transaction of its own and fails clears the shared queue,
* the other callbacks of the committed batch must still run.
*/
public function testFailingCallbackTransactionDoesNotDiscardSiblingCallbacks(): void
{
$tx = $this->txService();
$ran = [];

$tx->transaction(function () use ($tx, &$ran) {
$tx->afterCommit(function () use ($tx) {
$tx->transaction(function () {
throw new \RuntimeException('inner transaction fails');
});
});
$tx->afterCommit(function () use (&$ran) { $ran[] = 'second'; });
$tx->afterCommit(function () use (&$ran) { $ran[] = 'third'; });
});

$this->assertEquals(['second', 'third'], $ran);
}
}
113 changes: 113 additions & 0 deletions tests/OAuth2UserUpdateApiTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@
use App\libs\Auth\Models\IGroupSlugs;
use App\libs\OAuth2\IUserScopes;
use Auth\Group;
use App\libs\Auth\Factories\UserFactory;
use App\Mail\UserEmailVerificationRequest;
use Auth\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use LaravelDoctrine\ORM\Facades\EntityManager;

/**
Expand Down Expand Up @@ -107,11 +111,120 @@ public function testUserUpdate()
$this->assertTrue($response->first_name == $new_first_name);
}

/**
* @return \stdClass
*/
private function getUserRow(int $id): \stdClass
{
$row = DB::table('users')->where('id', $id)->first();
$this->assertNotNull($row);
return $row;
}

/**
* @return array
*/
private function getJsonHeaders(): array
{
return [
"HTTP_Authorization" => " Bearer " . $this->access_token,
"CONTENT_TYPE" => "application/json"
];
}

/**
* @return User a user with a verified email, so its spam type is Ham
*/
private function buildVerifiedUser(): User
{
$suffix = strtolower(str_random(12));
$user = UserFactory::build([
'first_name' => 'Ham',
'last_name' => 'User',
'email' => sprintf('ham.%s@test.com', $suffix),
'password' => '1Qaz2wsx!',
'active' => true,
'email_verified' => true,
'identifier' => 'ham.' . $suffix,
]);
EntityManager::persist($user);
EntityManager::flush();
$this->assertEquals(User::SpamTypeHam, $this->getUserRow($user->getId())->spam_type);
EntityManager::clear();
// the requests read the user from the database, like in production
$this->be(EntityManager::getRepository(User::class)->findOneBy(['identifier' => 'sebastian.marcet']), 'web');
return EntityManager::getRepository(User::class)->find($user->getId());
}

/**
* A verified user (spam type Ham) that changes the email or sets a bio must get it stored, and be
* re classified (spam type None).
*/
public function testUserUpdateEmailAndBioOfVerifiedUserIsStored()
{
$user = $this->buildVerifiedUser();
$new_email = sprintf('new.%s@test.com', strtolower(str_random(12)));

$response = $this->action
(
"PUT",
"Api\\OAuth2\\OAuth2UserApiController@update",
['id' => $user->getId()],
[],
[],
[],
$this->getJsonHeaders(),
json_encode(['first_name' => 'Renamed', 'email' => $new_email, 'bio' => 'a non empty bio'])
);

$this->assertResponseStatus(201);

$row = $this->getUserRow($user->getId());
$this->assertEquals('Renamed', $row->first_name);
$this->assertEquals($new_email, $row->email);
$this->assertEquals('a non empty bio', $row->bio);
$this->assertEquals(0, $row->email_verified);
$this->assertEquals(User::SpamTypeNone, $row->spam_type);

Mail::assertQueued(UserEmailVerificationRequest::class, 1);
Mail::assertQueued(UserEmailVerificationRequest::class, function (UserEmailVerificationRequest $mail) use ($new_email) {
return $mail->user_email === $new_email;
});
}

/**
* PUT /api/v1/users/me, sent by a verified user.
*/
public function testUserUpdateMeBioOfVerifiedUserIsStored()
{
$me = EntityManager::getRepository(User::class)->findOneBy(['identifier' => 'sebastian.marcet']);
// the seeded user is verified, make sure it is classified as Ham
DB::table('users')->where('id', $me->getId())->update(['spam_type' => User::SpamTypeHam]);
EntityManager::clear();

$this->json
(
"PUT",
// the bearer token audience is the app url, the request must target that host
$this->current_realm . "/api/v1/users/me",
['first_name' => 'Renamed', 'bio' => 'a non empty bio'],
$this->getJsonHeaders()
);

$this->assertResponseStatus(201);

$row = $this->getUserRow($me->getId());
$this->assertEquals('Renamed', $row->first_name);
$this->assertEquals('a non empty bio', $row->bio);
$this->assertEquals(User::SpamTypeNone, $row->spam_type);
}

protected function getScopes()
{
return [
"openid",
IUserScopes::Write,
IUserScopes::MeWrite,
];
}
}
Loading
Loading