Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
* Provider tokens are cast `encrypted` from here on. Rows stored before that are plain
* text, which the cast cannot read, so they are encrypted in place; the refresh token
* becomes text, as an encrypted value outgrows a string column.
*/
return new class extends Migration
{
private const COLUMNS = ['provider_token', 'provider_refresh_token'];

public function up(): void
{
Schema::table('social_accounts', function (Blueprint $table) {
$table->text('provider_refresh_token')->nullable()->change();
});

// MySQL runs this outside a transaction, so a retry after a crash part-way finds
// some rows already encrypted: those are left alone rather than encrypted twice.
$this->rewrite(fn (string $value): string => $this->isEncrypted($value) ? $value : Crypt::encryptString($value));

Check warning on line 27 in database/migrations/1000_00_00_000007_encrypt_social_account_tokens.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this 121 characters long line (which is greater than 120 authorized).

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_auth&issues=AaG24MLXtqj7RNvsV-17&open=AaG24MLXtqj7RNvsV-17&pullRequest=67
}

public function down(): void
{
$this->rewrite(fn (string $value): string => $this->isEncrypted($value) ? Crypt::decryptString($value) : $value);

Check warning on line 32 in database/migrations/1000_00_00_000007_encrypt_social_account_tokens.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this 121 characters long line (which is greater than 120 authorized).

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_auth&issues=AaG24MLXtqj7RNvsV-18&open=AaG24MLXtqj7RNvsV-18&pullRequest=67

Schema::table('social_accounts', function (Blueprint $table) {
$table->string('provider_refresh_token')->nullable()->change();
});
}

private function isEncrypted(string $value): bool
{
try {
Crypt::decryptString($value);

return true;
} catch (DecryptException) {
return false;
}
}

/** @param Closure(string): string $convert */
private function rewrite(Closure $convert): void
{
DB::table('social_accounts')->orderBy('id')->chunkById(500, function ($rows) use ($convert): void {
foreach ($rows as $row) {
$changes = [];

foreach (self::COLUMNS as $column) {
$value = $row->{$column};

// Empty becomes null: the cast skips decrypting null and nothing else.
if ($value === '') {
$changes[$column] = null;
} elseif ($value !== null) {
$changes[$column] = $convert($value);
}
}

if ($changes !== []) {
DB::table('social_accounts')->where('id', $row->id)->update($changes);
}
}
});
}
};
1 change: 1 addition & 0 deletions lang/en/socialite.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,5 @@
'account_already_linked' => 'This :provider account is already linked to another user',
'unsupported_provider' => 'The social provider :provider is not supported',
'registration_disabled' => 'New account registration is currently disabled',
'unverified_account' => 'An account with this email already exists. Sign in the way you did before, then connect this provider from your settings.',

Check warning on line 28 in lang/en/socialite.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this 152 characters long line (which is greater than 120 authorized).

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_auth&issues=AaG24MNZtqj7RNvsV-19&open=AaG24MNZtqj7RNvsV-19&pullRequest=67
];
4 changes: 3 additions & 1 deletion resources/boost/skills/saucebase-auth-development/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,9 @@ npx playwright test --project="@auth*" # E2E
## Gotchas

- `LoginRequest::validateCredentials()` validates without logging in — the controller handles `Auth::login()` separately
- Social users get a random password and are **not** marked verified — signing in with a provider is not proof of the address, and nobody has confirmed it (sc-713)
- Social sign-ups get **no** password (`users.password` is nullable), so `disconnectProvider()` refuses to remove their only provider until they add one; a made-up password let them lock themselves out (sc-1132). They are **not** marked verified: signing in with a provider is not proof of the address, and nobody has confirmed it (sc-713)
- `SocialAccount::provider_token` and `provider_refresh_token` are cast `encrypted` and `$hidden`: they let the app act on the provider as the user. `1000_00_00_000007` encrypts rows stored before the cast (sc-1132)
- A guest's social sign-in never links to an existing **unverified** account with the same email (`SocialiteException::unverifiedAccount()`): anyone can register with someone else's address, and linking would hand that account, and whoever knows its password, to the provider's owner. They sign in as before and connect the provider from Settings (sc-1130)
- Socialite redirect/callback routes are outside both guest and auth middleware groups
- `RegisterRequest::passedValidation()` hashes the password before the controller sees it
- Filament UserResource enforces single role (maxItems: 1) despite multi-select UI
Expand Down
5 changes: 5 additions & 0 deletions src/Exceptions/SocialiteException.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ public static function registrationDisabled(): self
return new self(trans('auth::socialite.registration_disabled'));
}

public static function unverifiedAccount(): self
{
return new self(trans('auth::socialite.unverified_account'));
}

public static function unsupportedProvider(string $provider): self
{
return new self(trans('auth::socialite.unsupported_provider', ['provider' => ucfirst($provider)]));
Expand Down
12 changes: 10 additions & 2 deletions src/Models/SocialAccount.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
* @property int $user_id
* @property string $provider
* @property string $provider_id
* @property string $provider_token
* @property string $provider_refresh_token
* @property string|null $provider_token
* @property string|null $provider_refresh_token
* @property Carbon|null $provider_token_expires_at
* @property string|null $provider_avatar_url
* @property Carbon|null $last_login_at
Expand All @@ -36,9 +36,17 @@ class SocialAccount extends Model
'last_login_at',
];

/** They let the app act on the provider as the user. */
protected $hidden = [
'provider_token',
'provider_refresh_token',
];

protected function casts(): array
{
return [
'provider_token' => 'encrypted',
'provider_refresh_token' => 'encrypted',
'provider_token_expires_at' => 'datetime',
'last_login_at' => 'datetime',
];
Expand Down
10 changes: 7 additions & 3 deletions src/Services/SocialiteService.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Laravel\Socialite\Facades\Socialite;
use Laravel\Socialite\Two\User as SocialiteUser;
use Modules\Auth\Exceptions\SocialiteException;
Expand Down Expand Up @@ -100,6 +98,10 @@ public function handleCallback(string $provider): User
}

$user = $this->createNewUser($socialiteUser, $avatarUrl);
} elseif (! $user->hasVerifiedEmail()) {
// Anyone can sign up with someone else's address; linking would hand this
// account to the provider's owner while its password may be another's.
throw SocialiteException::unverifiedAccount();
} else {
$this->updateUserAvatar($user, $avatarUrl);
}
Expand Down Expand Up @@ -198,7 +200,9 @@ private function createNewUser(SocialiteUser $socialiteUser, ?string $avatarUrl)
$user = User::create([
'name' => $socialiteUser->getName() ?: $socialiteUser->getNickname(),
'email' => $socialiteUser->getEmail(),
'password' => Hash::make(Str::random(32)), // Random password
// None: the provider is their way in until they add one, which is what stops
// them disconnecting it (disconnectProvider) and locking themselves out.
'password' => null,
'avatar' => $avatarUrl,
]);

Expand Down
66 changes: 66 additions & 0 deletions tests/Feature/EncryptSocialAccountTokensMigrationTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

namespace Modules\Auth\Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Modules\Auth\Models\SocialAccount;
use Tests\TestCase;

/** Tokens stored before the `encrypted` cast must still read once the upgrade has run. */
class EncryptSocialAccountTokensMigrationTest extends TestCase
{
use RefreshDatabase;

private function migration(): object
{
return require module_path('auth', 'database/migrations/1000_00_00_000007_encrypt_social_account_tokens.php');
}

public function test_plain_text_tokens_are_encrypted_and_read_back(): void
{
$user = $this->createUser();
$this->migration()->down();

$id = DB::table('social_accounts')->insertGetId([
'user_id' => $user->id,
'provider' => 'github',
'provider_id' => 'legacy-1',
'provider_token' => 'plain-access',
'provider_refresh_token' => 'plain-refresh',
'created_at' => now(),
'updated_at' => now(),
]);
DB::table('social_accounts')->insert([
'user_id' => $user->id,
'provider' => 'google',
'provider_id' => 'legacy-2',
'provider_token' => null,
'provider_refresh_token' => '',
'created_at' => now(),
'updated_at' => now(),
]);

$this->migration()->up();

$this->assertNotSame('plain-access', DB::table('social_accounts')->where('id', $id)->value('provider_token'));
$account = SocialAccount::findOrFail($id);
$this->assertSame('plain-access', $account->provider_token);
$this->assertSame('plain-refresh', $account->provider_refresh_token);
$this->assertNull(SocialAccount::where('provider_id', 'legacy-2')->sole()->provider_token);
// Empty is stored as null: the cast only skips decrypting null.
$this->assertNull(SocialAccount::where('provider_id', 'legacy-2')->sole()->provider_refresh_token);
}

/** MySQL runs it outside a transaction: a retry after a crash part-way must not encrypt twice. */
public function test_running_it_again_leaves_encrypted_tokens_alone(): void
{
$account = SocialAccount::factory()->create(['provider_token' => 'kept', 'provider_refresh_token' => 'kept-too']);

Check warning on line 58 in tests/Feature/EncryptSocialAccountTokensMigrationTest.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this 122 characters long line (which is greater than 120 authorized).

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_auth&issues=AaG24MG-tqj7RNvsV-14&open=AaG24MG-tqj7RNvsV-14&pullRequest=67

$this->migration()->up();

$account->refresh();
$this->assertSame('kept', $account->provider_token);
$this->assertSame('kept-too', $account->provider_refresh_token);
}
}
65 changes: 63 additions & 2 deletions tests/Feature/SocialiteCallbackTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Exceptions;
use Illuminate\Support\Facades\Notification;
use Laravel\Socialite\Facades\Socialite;
use Laravel\Socialite\Two\AbstractProvider;
use Laravel\Socialite\Two\User as SocialiteUser;
use Mockery\MockInterface;
use Modules\Auth\Models\SocialAccount;
use Modules\Auth\Notifications\LoginNotification;
use Modules\Auth\Settings\AuthSettings;
use Saucebase\Core\Facades\Home;
Expand Down Expand Up @@ -104,6 +107,25 @@
$this->assertAuthenticatedAs($user);
}

/**
* An unconfirmed address proves nothing about who made the account: anyone can sign up
* with someone else's email. Linking would hand the provider's owner an account whose
* password someone else may know.
*/
public function test_social_callback_does_not_link_to_an_unverified_account(): void
{
$this->enableGithub();

$user = User::factory()->unverified()->create();
$this->mockSocialiteDriver($this->makeSocialiteUser(email: $user->email));

$this->get(route('auth.socialite.callback', ['provider' => 'github']))
->assertRedirect(route('login'));

$this->assertGuest();
$this->assertDatabaseMissing('social_accounts', ['user_id' => $user->id]);
}

public function test_callback_sets_last_social_provider_cookie(): void
{
$this->enableGithub();
Expand Down Expand Up @@ -206,8 +228,8 @@
'user_id' => $user->id,
'provider' => 'github',
'provider_id' => 'gh-42',
'provider_refresh_token' => 'refresh-token',
]);
$this->assertSame('refresh-token', SocialAccount::where('provider_id', 'gh-42')->sole()->provider_refresh_token);

Check warning on line 232 in tests/Feature/SocialiteCallbackTest.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this 121 characters long line (which is greater than 120 authorized).

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_auth&issues=AaG24MLKtqj7RNvsV-15&open=AaG24MLKtqj7RNvsV-15&pullRequest=67
$this->assertSame(trans('auth::socialite.account_connected', ['provider' => 'Github']), session('toast')['message']);
}

Expand Down Expand Up @@ -282,6 +304,45 @@

$this->get(route('auth.socialite.callback', ['provider' => 'github']));

$this->assertDatabaseHas('social_accounts', ['provider_id' => 'gh-7', 'provider_refresh_token' => 'refresh-token']);
$account = SocialAccount::where('provider_id', 'gh-7')->sole();
$this->assertSame('refresh-token', $account->provider_refresh_token);
$this->assertSame('access-token', $account->provider_token);
}

/** They let the app act on the provider as the user: never stored readable, never serialised. */
public function test_provider_tokens_are_encrypted_at_rest_and_hidden(): void
{
$this->enableGithub();
$this->mockSocialiteDriver($this->makeSocialiteUser(id: 'gh-8'));

$this->get(route('auth.socialite.callback', ['provider' => 'github']));

$row = DB::table('social_accounts')->where('provider_id', 'gh-8')->sole();
$this->assertNotSame('access-token', $row->provider_token);
$this->assertNotSame('refresh-token', $row->provider_refresh_token);
$this->assertSame('access-token', Crypt::decryptString($row->provider_token));

$serialised = SocialAccount::where('provider_id', 'gh-8')->sole()->toArray();
$this->assertArrayNotHasKey('provider_token', $serialised);
$this->assertArrayNotHasKey('provider_refresh_token', $serialised);
}

/**
* A provider sign-up sets no password, so the provider stays its only way in until the
* user adds one: a made-up password would let them disconnect it and lock themselves out.
*/
public function test_a_social_sign_up_has_no_password_and_cannot_drop_its_only_sign_in(): void
{
$this->enableGithub();
$this->mockSocialiteDriver($this->makeSocialiteUser(id: 'gh-9', email: 'only@example.com'));

$this->get(route('auth.socialite.callback', ['provider' => 'github']));

$user = User::where('email', 'only@example.com')->sole();
$this->assertNull($user->password);

$this->actingAs($user)->delete(route('auth.socialite.disconnect', ['provider' => 'github']));

$this->assertDatabaseHas('social_accounts', ['user_id' => $user->id, 'provider' => 'github']);
}
}
4 changes: 2 additions & 2 deletions tests/Unit/SocialiteServiceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,8 @@
'user_id' => $user->id,
'provider' => 'google',
'provider_id' => 'provider-123',
'provider_token' => 'new-token',
]);
$this->assertSame('new-token', SocialAccount::where('provider_id', 'provider-123')->sole()->provider_token);
$this->assertDatabaseCount('social_accounts', 1);
}

Expand Down Expand Up @@ -261,8 +261,8 @@
$this->assertEquals($existingUser->id, $user->id);
$this->assertDatabaseHas('social_accounts', [
'provider_id' => 'existing-provider-id',
'provider_token' => 'updated-token',
]);
$this->assertSame('updated-token', SocialAccount::where('provider_id', 'existing-provider-id')->sole()->provider_token);

Check warning on line 265 in tests/Unit/SocialiteServiceTest.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this 128 characters long line (which is greater than 120 authorized).

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_auth&issues=AaG24MLWtqj7RNvsV-16&open=AaG24MLWtqj7RNvsV-16&pullRequest=67
Event::assertNotDispatched(Registered::class);
}

Expand Down
Loading