Skip to content

An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.

fix(auth): handle concurrent OAuth identity creation safely

Andras Bacsai3b08be1429a4
diff --git a/app/Services/Auth/OauthLoginService.php b/app/Services/Auth/OauthLoginService.php
index c093e290f0..2ec8f88e3e 100644
--- a/app/Services/Auth/OauthLoginService.php
+++ b/app/Services/Auth/OauthLoginService.php
@@ -7,6 +7,7 @@ use App\Models\OauthIdentity;
use App\Models\OauthSetting;
use App\Models\Team;
use App\Models\User;
+use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
@@ -37,50 +38,59 @@ class OauthLoginService
{
$provider = $oauthSetting->provider;
$providerUserId = $oauthUser->id ?? null;
- if (! is_scalar($providerUserId) || trim((string) $providerUserId) === '') {
+ if (
+ (! is_string($providerUserId) && ! is_int($providerUserId))
+ || (is_string($providerUserId) && trim($providerUserId) === '')
+ ) {
throw new HttpException(403, 'OAuth provider did not return a valid user ID');
}
$providerUserId = (string) $providerUserId;
$rawClaims = is_array($oauthUser->user ?? null) ? $oauthUser->user : [];
- return DB::transaction(function () use ($oauthUser, $oauthSetting, $email, $provider, $providerUserId, $rawClaims) {
- $identity = OauthIdentity::where([
- 'provider' => $provider,
- 'issuer' => $provider,
- 'provider_user_id' => $providerUserId,
- ])->first();
+ $identityKey = [
+ 'provider' => $provider,
+ 'issuer' => $provider,
+ 'provider_user_id' => $providerUserId,
+ ];
- if ($identity) {
- $identity->update([
- 'email' => $email,
- 'raw_claims' => $rawClaims,
- 'last_login_at' => now(),
- ]);
+ try {
+ return DB::transaction(function () use ($oauthUser, $oauthSetting, $email, $provider, $providerUserId, $rawClaims, $identityKey): User {
+ $identity = OauthIdentity::where($identityKey)->first();
- return $identity->user;
- }
+ if ($identity) {
+ $identity->update([
+ 'email' => $email,
+ 'raw_claims' => $rawClaims,
+ 'last_login_at' => now(),
+ ]);
- $user = User::whereEmail($email)->first();
- if (! $user) {
- if (! $this->canCreateUser($oauthSetting)) {
- throw new HttpException(403, 'Registration is disabled');
+ return $identity->user;
}
- $user = $this->createUser($oauthUser->name ?: $email, $email, $oauthSetting);
- }
+ $user = User::whereEmail($email)->first();
+ if (! $user) {
+ if (! $this->canCreateUser($oauthSetting)) {
+ throw new HttpException(403, 'Registration is disabled');
+ }
- OauthIdentity::create([
- 'user_id' => $user->id,
- 'provider' => $provider,
- 'issuer' => $provider,
- 'provider_user_id' => $providerUserId,
- 'email' => $email,
- 'raw_claims' => $rawClaims,
- 'last_login_at' => now(),
- ]);
+ $user = $this->createUser($oauthUser->name ?: $email, $email, $oauthSetting);
+ }
- return $user;
- });
+ OauthIdentity::create([
+ 'user_id' => $user->id,
+ 'provider' => $provider,
+ 'issuer' => $provider,
+ 'provider_user_id' => $providerUserId,
+ 'email' => $email,
+ 'raw_claims' => $rawClaims,
+ 'last_login_at' => now(),
+ ]);
+
+ return $user;
+ });
+ } catch (UniqueConstraintViolationException $exception) {
+ return OauthIdentity::where($identityKey)->first()?->user ?? throw $exception;
+ }
}
private function resolveOidcUser(object $oauthUser, OauthSetting $oauthSetting, string $email): User
@@ -104,53 +114,59 @@ class OauthLoginService
$rawClaims = is_array($oauthUser->user ?? null) ? $oauthUser->user : [];
- return DB::transaction(function () use ($oauthUser, $oauthSetting, $email, $issuer, $subject, $emailVerified, $rawClaims) {
- $identity = OauthIdentity::where([
- 'provider' => 'oidc',
- 'issuer' => $issuer,
- 'provider_user_id' => $subject,
- ])->first();
+ $identityKey = [
+ 'provider' => 'oidc',
+ 'issuer' => $issuer,
+ 'provider_user_id' => $subject,
+ ];
- if ($identity) {
- $identity->update([
- 'email' => $email,
- 'raw_claims' => $rawClaims,
- 'last_login_at' => now(),
- ]);
+ try {
+ return DB::transaction(function () use ($oauthUser, $oauthSetting, $email, $issuer, $subject, $emailVerified, $rawClaims, $identityKey): User {
+ $identity = OauthIdentity::where($identityKey)->first();
- return $identity->user;
- }
+ if ($identity) {
+ $identity->update([
+ 'email' => $email,
+ 'raw_claims' => $rawClaims,
+ 'last_login_at' => now(),
+ ]);
- $user = User::whereEmail($email)->first();
+ return $identity->user;
+ }
- // Linking a new OIDC identity to an existing local account by email
- // is account takeover unless the provider attests the email. This
- // guard is independent of the require_email_verified toggle, which
- // only governs the broader login flow.
- if ($user && ! $emailVerified) {
- throw new HttpException(403, 'OIDC provider must verify the email address before linking to an existing account');
- }
+ $user = User::whereEmail($email)->first();
- if (! $user) {
- if (! $this->canCreateUser($oauthSetting)) {
- throw new HttpException(403, 'Registration is disabled');
+ // Linking a new OIDC identity to an existing local account by email
+ // is account takeover unless the provider attests the email. This
+ // guard is independent of the require_email_verified toggle, which
+ // only governs the broader login flow.
+ if ($user && ! $emailVerified) {
+ throw new HttpException(403, 'OIDC provider must verify the email address before linking to an existing account');
}
- $user = $this->createUser($oauthUser->name ?: $email, $email, $oauthSetting);
- }
+ if (! $user) {
+ if (! $this->canCreateUser($oauthSetting)) {
+ throw new HttpException(403, 'Registration is disabled');
+ }
- OauthIdentity::create([
- 'user_id' => $user->id,
- 'provider' => 'oidc',
- 'issuer' => $issuer,
- 'provider_user_id' => $subject,
- 'email' => $email,
- 'raw_claims' => $rawClaims,
- 'last_login_at' => now(),
- ]);
+ $user = $this->createUser($oauthUser->name ?: $email, $email, $oauthSetting);
+ }
- return $user;
- });
+ OauthIdentity::create([
+ 'user_id' => $user->id,
+ 'provider' => 'oidc',
+ 'issuer' => $issuer,
+ 'provider_user_id' => $subject,
+ 'email' => $email,
+ 'raw_claims' => $rawClaims,
+ 'last_login_at' => now(),
+ ]);
+
+ return $user;
+ });
+ } catch (UniqueConstraintViolationException $exception) {
+ return OauthIdentity::where($identityKey)->first()?->user ?? throw $exception;
+ }
}
private function canCreateUser(OauthSetting $oauthSetting): bool
diff --git a/tests/Feature/OauthControllerTest.php b/tests/Feature/OauthControllerTest.php
index f0225e3357..4671183ae7 100644
--- a/tests/Feature/OauthControllerTest.php
+++ b/tests/Feature/OauthControllerTest.php
@@ -5,7 +5,10 @@ use App\Models\OauthIdentity;
use App\Models\OauthSetting;
use App\Models\User;
use App\Services\Auth\OauthLoginService;
+use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Event;
use Illuminate\Support\Once;
use Laravel\Socialite\Facades\Socialite;
use Symfony\Component\HttpKernel\Exception\HttpException;
@@ -92,6 +95,38 @@ it('never moves an existing oauth identity when the provider email changes', fun
->and($identity->user_id)->not->toBe($otherUser->id);
});
+it('continues oauth login when another request creates the identity first', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $eventName = 'eloquent.creating: '.OauthIdentity::class;
+
+ Event::listen($eventName, function (OauthIdentity $identity): void {
+ $attributes = $identity->getAttributes();
+
+ DB::afterRollBack(fn () => DB::table('oauth_identities')->insert($attributes));
+
+ throw new UniqueConstraintViolationException(
+ DB::getDefaultConnection(),
+ 'insert into oauth_identities',
+ [],
+ new PDOException('duplicate identity'),
+ );
+ });
+
+ try {
+ $resolvedUser = app(OauthLoginService::class)->login('google', (object) [
+ 'email' => '[email protected]',
+ 'name' => 'Race User',
+ 'id' => 'google-race-id',
+ ], OauthSetting::where('provider', 'google')->firstOrFail());
+ } finally {
+ Event::forget($eventName);
+ }
+
+ expect($resolvedUser->is($user))->toBeTrue()
+ ->and(OauthIdentity::where('provider_user_id', 'google-race-id')->count())->toBe(1);
+ $this->assertAuthenticatedAs($user);
+});
+
it('rejects oauth logins when the provider does not return an email address', function (?string $providerEmail) {
config()->set('app.maintenance.driver', 'file');
InstanceSettings::firstOrCreate([
@@ -150,4 +185,7 @@ it('rejects oauth logins when the provider does not return a valid user id', fun
'missing id' => ['missing'],
'blank id' => [' '],
'non-scalar id' => [[]],
+ 'true id' => [true],
+ 'false id' => [false],
+ 'float id' => [1.0],
]);
diff --git a/tests/Feature/OidcOauthControllerTest.php b/tests/Feature/OidcOauthControllerTest.php
index 21b335016e..084347f66d 100644
--- a/tests/Feature/OidcOauthControllerTest.php
+++ b/tests/Feature/OidcOauthControllerTest.php
@@ -6,7 +6,11 @@ use App\Models\OauthIdentity;
use App\Models\OauthSetting;
use App\Models\Team;
use App\Models\User;
+use App\Services\Auth\OauthLoginService;
+use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Once;
use Laravel\Socialite\Facades\Socialite;
@@ -73,6 +77,44 @@ it('logs in a user through an existing oidc identity', function () {
$this->assertAuthenticatedAs($user);
});
+it('continues oidc login when another request creates the identity first', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $eventName = 'eloquent.creating: '.OauthIdentity::class;
+
+ Event::listen($eventName, function (OauthIdentity $identity): void {
+ $attributes = $identity->getAttributes();
+
+ DB::afterRollBack(fn () => DB::table('oauth_identities')->insert($attributes));
+
+ throw new UniqueConstraintViolationException(
+ DB::getDefaultConnection(),
+ 'insert into oauth_identities',
+ [],
+ new PDOException('duplicate identity'),
+ );
+ });
+
+ try {
+ $resolvedUser = app(OauthLoginService::class)->login('oidc', (new OidcUser)->setRaw([
+ 'iss' => 'https://idp.example.com',
+ 'sub' => 'oidc-race-id',
+ 'email' => '[email protected]',
+ 'email_verified' => true,
+ 'name' => 'Race User',
+ ])->map([
+ 'id' => 'oidc-race-id',
+ 'name' => 'Race User',
+ 'email' => '[email protected]',
+ ]), OauthSetting::where('provider', 'oidc')->firstOrFail());
+ } finally {
+ Event::forget($eventName);
+ }
+
+ expect($resolvedUser->is($user))->toBeTrue()
+ ->and(OauthIdentity::where('provider_user_id', 'oidc-race-id')->count())->toBe(1);
+ $this->assertAuthenticatedAs($user);
+});
+
it('creates a new oidc user when provider registration is allowed while normal registration is disabled', function () {
OauthSetting::where('provider', 'oidc')->update(['allow_registration' => true]);