trypost/tests/Feature/Social/LinkedInControllerTest.php
Falconiere Barbosa 410eb9612e fix(linkedin): drop deprecated r_basicprofile from default scopes
Make r_basicprofile opt-in via LINKEDIN_EXTRA_SCOPES so self-hosted users
unblock by default and ops with legacy/enterprise products keep working.

Why
---
LinkedIn rejects OAuth authorize requests with a generic "Bummer,
something went wrong" page when an app asks for a scope it can't grant.
`r_basicprofile` is a legacy scope deprecated in 2018; new LinkedIn dev
apps don't have it, so every self-hosted user hits the rejection
immediately on `/connect/linkedin`.

The two products LinkedIn actually grants to standard apps today are:

- Sign In with LinkedIn using OpenID Connect → `openid profile email`
- Share on LinkedIn                          → `w_member_social`

That set is enough for the connect flow. The only piece of data
`r_basicprofile` was buying us is `/v2/me`'s `vanityName` (pretty
`linkedin.com/in/<slug>`). `fetchVanityName()` already handles HTTP
failure gracefully (returns null), and the only downstream consumer —
`LinkedInPagePublisher`'s post-URL builder — already falls back to a
numeric `linkedin.com/feed/update/<id>` URL when `$account->username`
is null.

Backward compatibility
----------------------
Ops with legacy or enterprise LinkedIn products approved on their dev
app (so they DO have `r_basicprofile`) can opt back in via env:

    LINKEDIN_EXTRA_SCOPES=r_basicprofile

`LinkedInController::resolveScopes()` merges this comma-separated list
into the default scope array. The connect flow's `Socialite::scopes()`
call then includes the legacy scope, preserving the pre-PR behaviour
end-to-end (including `vanityName` lookup).

Net effect for users without `r_basicprofile`:
- Connect flow works (was previously rejected by LinkedIn).
- Posts publish exactly the same way.
- Generated post URLs use the numeric form instead of the vanity slug.

Tests
-----
- `linkedin connect requests the default scope set when LINKEDIN_EXTRA_SCOPES is unset`
- `linkedin connect appends LINKEDIN_EXTRA_SCOPES to the default scope set`
- Existing `splits comma-separated approvedScopes` fixture updated to
  match the new default set.
2026-06-10 13:51:07 -03:00

253 lines
8.9 KiB
PHP

<?php
declare(strict_types=1);
use App\Enums\SocialAccount\Platform;
use App\Enums\SocialAccount\Status;
use App\Enums\UserWorkspace\Role;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use Illuminate\Support\Facades\Http;
use Laravel\Socialite\Facades\Socialite;
use Laravel\Socialite\Two\User as SocialiteUser;
beforeEach(function () {
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
$this->user->update(['current_workspace_id' => $this->workspace->id]);
$this->workspace->members()->attach($this->user->id, ['role' => Role::Member->value]);
});
test('linkedin connect redirects to oauth provider', function () {
$driverMock = Mockery::mock();
$driverMock->shouldReceive('scopes')->andReturnSelf();
$driverMock->shouldReceive('redirect')->andReturn(Mockery::mock([
'getTargetUrl' => 'https://www.linkedin.com/oauth/v2/authorization?test=1',
]));
Socialite::shouldReceive('driver')
->with('linkedin')
->andReturn($driverMock);
$response = $this->actingAs($this->user)
->withHeader('X-Inertia', 'true')
->get(route('app.social.linkedin.connect'));
$response->assertStatus(409); // Inertia::location returns 409 with X-Inertia header
expect(session('social_connect_workspace'))->toBe($this->workspace->id);
});
test('linkedin connect requests the default scope set when LINKEDIN_EXTRA_SCOPES is unset', function () {
config(['services.linkedin.extra_scopes' => null]);
$captured = [];
$driverMock = Mockery::mock();
$driverMock->shouldReceive('scopes')
->withArgs(function (array $scopes) use (&$captured) {
$captured = $scopes;
return true;
})
->andReturnSelf();
$driverMock->shouldReceive('redirect')->andReturn(Mockery::mock([
'getTargetUrl' => 'https://www.linkedin.com/oauth/v2/authorization?test=1',
]));
Socialite::shouldReceive('driver')
->with('linkedin')
->andReturn($driverMock);
$this->actingAs($this->user)
->withHeader('X-Inertia', 'true')
->get(route('app.social.linkedin.connect'));
expect($captured)->toEqualCanonicalizing([
'openid', 'profile', 'email', 'w_member_social',
]);
});
test('linkedin connect appends LINKEDIN_EXTRA_SCOPES to the default scope set', function () {
// Backward-compatibility: ops who have legacy products approved on
// their LinkedIn app (e.g. r_basicprofile) opt back in via env.
config(['services.linkedin.extra_scopes' => 'r_basicprofile, r_emailaddress']);
$captured = [];
$driverMock = Mockery::mock();
$driverMock->shouldReceive('scopes')
->withArgs(function (array $scopes) use (&$captured) {
$captured = $scopes;
return true;
})
->andReturnSelf();
$driverMock->shouldReceive('redirect')->andReturn(Mockery::mock([
'getTargetUrl' => 'https://www.linkedin.com/oauth/v2/authorization?test=1',
]));
Socialite::shouldReceive('driver')
->with('linkedin')
->andReturn($driverMock);
$this->actingAs($this->user)
->withHeader('X-Inertia', 'true')
->get(route('app.social.linkedin.connect'));
expect($captured)->toEqualCanonicalizing([
'openid', 'profile', 'email', 'w_member_social',
'r_basicprofile', 'r_emailaddress',
]);
});
test('linkedin oauth callback creates account', function () {
session([
'social_connect_workspace' => $this->workspace->id,
]);
$socialiteUser = Mockery::mock(SocialiteUser::class);
$socialiteUser->shouldReceive('getId')->andReturn('abc123xyz');
$socialiteUser->shouldReceive('getNickname')->andReturn(null);
$socialiteUser->shouldReceive('getName')->andReturn('John Doe');
$socialiteUser->shouldReceive('getAvatar')->andReturn(null);
$socialiteUser->token = 'test-access-token';
$socialiteUser->refreshToken = 'test-refresh-token';
$socialiteUser->expiresIn = 5184000; // 60 days
$socialiteUser->approvedScopes = ['openid', 'profile', 'email', 'w_member_social'];
Socialite::shouldReceive('driver')
->with('linkedin')
->andReturn(Mockery::mock([
'user' => $socialiteUser,
]));
Http::fake([
'https://api.linkedin.com/v2/me*' => Http::response([
'id' => 'abc123xyz',
'vanityName' => 'johndoe',
'localizedFirstName' => 'John',
'localizedLastName' => 'Doe',
], 200),
]);
$response = $this->actingAs($this->user)->get(route('app.social.linkedin.callback'));
$response->assertOk();
$response->assertViewIs('auth.social-callback');
$response->assertViewHas('success', true);
$this->assertDatabaseHas('social_accounts', [
'workspace_id' => $this->workspace->id,
'platform' => Platform::LinkedIn->value,
'platform_user_id' => 'abc123xyz',
'username' => 'johndoe',
'status' => Status::Connected->value,
]);
});
test('linkedin oauth callback splits comma-separated approvedScopes before saving', function () {
session(['social_connect_workspace' => $this->workspace->id]);
$socialiteUser = Mockery::mock(SocialiteUser::class);
$socialiteUser->shouldReceive('getId')->andReturn('abc123xyz');
$socialiteUser->shouldReceive('getNickname')->andReturn(null);
$socialiteUser->shouldReceive('getName')->andReturn('John Doe');
$socialiteUser->shouldReceive('getAvatar')->andReturn(null);
$socialiteUser->token = 'test-access-token';
$socialiteUser->refreshToken = 'test-refresh-token';
$socialiteUser->expiresIn = 5184000;
// LinkedIn returns scopes comma-separated; Socialite's LinkedInProvider
// splits on space (the OAuth 2.0 default), so approvedScopes lands as
// a single-element array with the whole CSV inside. The save path
// must normalize back to individual tokens.
$socialiteUser->approvedScopes = ['email,openid,profile,w_member_social'];
Socialite::shouldReceive('driver')
->with('linkedin')
->andReturn(Mockery::mock(['user' => $socialiteUser]));
Http::fake([
'https://api.linkedin.com/v2/me*' => Http::response([
'id' => 'abc123xyz',
'vanityName' => 'johndoe',
], 200),
]);
$this->actingAs($this->user)->get(route('app.social.linkedin.callback'));
$account = SocialAccount::where('platform_user_id', 'abc123xyz')->first();
expect($account->scopes)->toEqualCanonicalizing([
'email', 'openid', 'profile', 'w_member_social',
]);
});
test('linkedin callback fails with expired session', function () {
// No session data - simulating expired session
$response = $this->actingAs($this->user)->get(route('app.social.linkedin.callback'));
$response->assertOk();
$response->assertViewHas('success', false);
$response->assertViewHas('message', 'Session expired. Please try again.');
});
test('user can connect multiple linkedin accounts', function () {
SocialAccount::factory()->linkedin()->create([
'workspace_id' => $this->workspace->id,
'platform_user_id' => 'abc123xyz',
]);
session([
'social_connect_workspace' => $this->workspace->id,
]);
$socialiteUser = Mockery::mock(SocialiteUser::class);
$socialiteUser->shouldReceive('getId')->andReturn('xyz789abc');
$socialiteUser->shouldReceive('getNickname')->andReturn(null);
$socialiteUser->shouldReceive('getName')->andReturn('Jane Doe');
$socialiteUser->shouldReceive('getAvatar')->andReturn(null);
$socialiteUser->token = 'new-access-token';
$socialiteUser->refreshToken = 'new-refresh-token';
$socialiteUser->expiresIn = 5184000;
$socialiteUser->approvedScopes = ['openid', 'profile', 'email', 'w_member_social'];
Socialite::shouldReceive('driver')
->with('linkedin')
->andReturn(Mockery::mock([
'user' => $socialiteUser,
]));
Http::fake([
'https://api.linkedin.com/v2/me*' => Http::response([
'vanityName' => 'janedoe',
], 200),
]);
$response = $this->actingAs($this->user)->get(route('app.social.linkedin.callback'));
$response->assertOk();
$response->assertViewHas('success', true);
expect($this->workspace->socialAccounts()->where('platform', Platform::LinkedIn)->count())->toBe(2);
});
test('linkedin callback handles oauth errors gracefully', function () {
session([
'social_connect_workspace' => $this->workspace->id,
]);
$mock = Mockery::mock();
$mock->shouldReceive('user')->andThrow(new Exception('OAuth error'));
Socialite::shouldReceive('driver')
->with('linkedin')
->andReturn($mock);
$response = $this->actingAs($this->user)->get(route('app.social.linkedin.callback'));
$response->assertOk();
$response->assertViewHas('success', false);
$response->assertViewHas('message', 'Error connecting account. Please try again.');
});