-
Notifications
You must be signed in to change notification settings - Fork 37
fix(integration-github): fetch primary email from /user/emails #367
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
172 changes: 172 additions & 0 deletions
172
app-modules/identity/tests/Feature/Auth/HandleOAuthCallbackActionTest.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,172 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| use App\Contracts\OAuthClientContract; | ||
| use He4rt\Identity\Auth\Actions\HandleOAuthCallbackAction; | ||
| use He4rt\Identity\Auth\DTOs\OAuthAccessDTO; | ||
| use He4rt\Identity\Auth\DTOs\OAuthStateDTO; | ||
| use He4rt\Identity\Auth\DTOs\OAuthUserDTO; | ||
| use He4rt\Identity\Auth\Enums\OAuthIntent; | ||
| use He4rt\Identity\ExternalIdentity\Enums\IdentityProvider; | ||
| use He4rt\Identity\ExternalIdentity\Models\ExternalIdentity; | ||
| use He4rt\Identity\Tenant\Models\Tenant; | ||
| use He4rt\Identity\User\Models\User; | ||
| use He4rt\IntegrationGithub\OAuth\GitHubOAuthClient; | ||
|
|
||
| use function Pest\Laravel\actingAs; | ||
| use function Pest\Laravel\assertDatabaseCount; | ||
|
|
||
| function fakeOAuthAccess(): OAuthAccessDTO | ||
| { | ||
| return new class('gh-access', 'gh-refresh', 3_600) extends OAuthAccessDTO | ||
| { | ||
| public static function make(array $payload): self | ||
| { | ||
| return new self('gh-access', 'gh-refresh', 3_600); | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| function fakeGithubUser(string $email, string $providerId): OAuthUserDTO | ||
| { | ||
| return new class(fakeOAuthAccess(), $providerId, IdentityProvider::GitHub, 'octocat', 'Octo Cat', $email, avatarUrl: null) extends OAuthUserDTO | ||
| { | ||
| public static function make(OAuthAccessDTO $credentials, array $payload): self | ||
| { | ||
| return new self($credentials, '', IdentityProvider::GitHub, '', '', null, null); | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Bind a stub GitHub client so the orchestrator never hits the network. | ||
| */ | ||
| function bindFakeGithubClient(OAuthUserDTO $githubUser): void | ||
| { | ||
| app()->instance(GitHubOAuthClient::class, new readonly class($githubUser) implements OAuthClientContract | ||
| { | ||
| public function __construct(private OAuthUserDTO $githubUser) {} | ||
|
|
||
| public function redirectUrl(?OAuthStateDTO $state = null): string | ||
| { | ||
| return 'https://github.test/oauth'; | ||
| } | ||
|
|
||
| public function auth(string $code): OAuthAccessDTO | ||
| { | ||
| return fakeOAuthAccess(); | ||
| } | ||
|
|
||
| public function getAuthenticatedUser(OAuthAccessDTO $credentials): OAuthUserDTO | ||
| { | ||
| return $this->githubUser; | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| test('links a second provider to the logged-in user even when the email differs', function (): void { | ||
| // A user who originally signed up via Discord (discord@discord.com)... | ||
| $tenant = Tenant::factory()->create(); | ||
| $discordUser = User::factory()->create(['email' => 'discord@discord.com']); | ||
|
|
||
| ExternalIdentity::factory()->create([ | ||
| 'tenant_id' => $tenant->id, | ||
| 'model_type' => (new User)->getMorphClass(), | ||
| 'model_id' => $discordUser->id, | ||
| 'connected_by' => $discordUser->id, | ||
| 'provider' => IdentityProvider::Discord, | ||
| 'external_account_id' => 'discord-123', | ||
| ]); | ||
|
|
||
| actingAs($discordUser); | ||
|
|
||
| // ...now logs in with GitHub, whose account carries a *different* email. | ||
| bindFakeGithubClient(fakeGithubUser(email: 'github@github.com', providerId: 'gh-999')); | ||
|
|
||
| $state = new OAuthStateDTO( | ||
| intent: OAuthIntent::Link, | ||
| provider: IdentityProvider::GitHub, | ||
| panel: 'app', | ||
| tenant: $tenant->slug, | ||
| returnUrl: 'https://he4rt.test/app', | ||
| ); | ||
|
|
||
| $result = resolve(HandleOAuthCallbackAction::class) | ||
| ->execute($state, IdentityProvider::GitHub, 'auth-code'); | ||
|
|
||
| // The flow links to the existing logged-in user — it does not fork a new | ||
| // one, and the differing email is a non-event (no merge conflict). | ||
| expect($result->intent)->toBe(OAuthIntent::Link) | ||
| ->and($result->user->id)->toBe($discordUser->id) | ||
| ->and($result->mergeConflict)->toBeNull(); | ||
|
|
||
| // The current user keeps their original email column untouched. | ||
| expect($discordUser->fresh()->email)->toBe('discord@discord.com'); | ||
|
|
||
| // No user is created from the GitHub email — nothing was forked. | ||
| expect(User::query()->where('email', 'github@github.com')->exists())->toBeFalse(); | ||
|
|
||
| // The GitHub identity is attached to the Discord user, and the GitHub email | ||
| // lives only in the identity metadata. | ||
| $githubIdentity = ExternalIdentity::query() | ||
| ->where('provider', IdentityProvider::GitHub) | ||
| ->where('external_account_id', 'gh-999') | ||
| ->first(); | ||
|
|
||
| expect($githubIdentity)->not->toBeNull() | ||
| ->and($githubIdentity->model_id)->toBe($discordUser->id) | ||
| ->and($githubIdentity->metadata['email'])->toBe('github@github.com'); | ||
| }); | ||
|
|
||
| test('forks a separate account when a logged-out github login has a different email', function (): void { | ||
| // Same starting point — a Discord user (discord@discord.com). | ||
| $tenant = Tenant::factory()->create(); | ||
| $discordUser = User::factory()->create(['email' => 'discord@discord.com']); | ||
|
|
||
| ExternalIdentity::factory()->create([ | ||
| 'tenant_id' => $tenant->id, | ||
| 'model_type' => (new User)->getMorphClass(), | ||
| 'model_id' => $discordUser->id, | ||
| 'connected_by' => $discordUser->id, | ||
| 'provider' => IdentityProvider::Discord, | ||
| 'external_account_id' => 'discord-123', | ||
| ]); | ||
|
|
||
| // ...but this time they are LOGGED OUT (no actingAs) and sign in from the | ||
| // login page with GitHub, intent = Login. With no shared email and no prior | ||
| // GitHub link, there is nothing to correlate on, so a new account is forked | ||
| // (Option B: email is the only merge key on the Login path). | ||
| bindFakeGithubClient(fakeGithubUser(email: 'github@github.com', providerId: 'gh-999')); | ||
|
|
||
| $state = new OAuthStateDTO( | ||
| intent: OAuthIntent::Login, | ||
| provider: IdentityProvider::GitHub, | ||
| panel: 'app', | ||
| tenant: $tenant->slug, | ||
| returnUrl: 'https://he4rt.test/app', | ||
| ); | ||
|
|
||
| $result = resolve(HandleOAuthCallbackAction::class) | ||
| ->execute($state, IdentityProvider::GitHub, 'auth-code'); | ||
|
|
||
| // A brand-new user is created — NOT the existing Discord user. | ||
| expect($result->intent)->toBe(OAuthIntent::Login) | ||
| ->and($result->user->id)->not->toBe($discordUser->id) | ||
| ->and($result->user->email)->toBe('github@github.com'); | ||
|
|
||
| // The original Discord account is left completely untouched. | ||
| expect($discordUser->fresh()->email)->toBe('discord@discord.com'); | ||
|
|
||
| // The GitHub identity is attached to the new forked user, not the Discord one. | ||
| $githubIdentity = ExternalIdentity::query() | ||
| ->where('provider', IdentityProvider::GitHub) | ||
| ->where('external_account_id', 'gh-999') | ||
| ->first(); | ||
|
|
||
| expect($githubIdentity)->not->toBeNull() | ||
| ->and($githubIdentity->model_id)->toBe($result->user->id) | ||
| ->and($githubIdentity->model_id)->not->toBe($discordUser->id); | ||
|
|
||
| assertDatabaseCount(User::class, 3); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
28 changes: 28 additions & 0 deletions
28
app-modules/integration-github/src/Transport/Requests/Users/GetUserEmails.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace He4rt\IntegrationGithub\Transport\Requests\Users; | ||
|
|
||
| use Saloon\Enums\Method; | ||
| use Saloon\Http\Auth\TokenAuthenticator; | ||
| use Saloon\Http\Request; | ||
|
|
||
| final class GetUserEmails extends Request | ||
| { | ||
| protected Method $method = Method::GET; | ||
|
|
||
| public function __construct( | ||
| private readonly string $accessToken, | ||
| ) {} | ||
|
|
||
| public function resolveEndpoint(): string | ||
| { | ||
| return '/user/emails'; | ||
| } | ||
|
|
||
| protected function defaultAuth(): TokenAuthenticator | ||
| { | ||
| return new TokenAuthenticator($this->accessToken); | ||
| } | ||
| } |
100 changes: 100 additions & 0 deletions
100
app-modules/integration-github/tests/Feature/GitHubOAuthClientTest.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| use He4rt\Identity\Auth\Exceptions\OAuthFlowException; | ||
| use He4rt\Identity\ExternalIdentity\Enums\IdentityProvider; | ||
| use He4rt\IntegrationGithub\OAuth\DTO\GitHubOAuthAccessDTO; | ||
| use He4rt\IntegrationGithub\OAuth\GitHubOAuthClient; | ||
| use He4rt\IntegrationGithub\Transport\GitHubApiConnector; | ||
| use He4rt\IntegrationGithub\Transport\GitHubOAuthConnector; | ||
| use He4rt\IntegrationGithub\Transport\Requests\Users\GetCurrentUser; | ||
| use He4rt\IntegrationGithub\Transport\Requests\Users\GetUserEmails; | ||
| use Saloon\Http\Faking\MockClient; | ||
| use Saloon\Http\Faking\MockResponse; | ||
|
|
||
| /** | ||
| * @param array<class-string, MockResponse> $responses | ||
| */ | ||
| function githubOAuthClient(array $responses): GitHubOAuthClient | ||
| { | ||
| $api = tap( | ||
| new GitHubApiConnector(), | ||
| fn (GitHubApiConnector $connector) => $connector->withMockClient(new MockClient($responses)), | ||
| ); | ||
|
|
||
| return new GitHubOAuthClient( | ||
| oauthConnector: new GitHubOAuthConnector(clientId: 'cid', clientSecret: 'secret'), | ||
| apiConnector: $api, | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| * @param array<string, mixed> $overrides | ||
| */ | ||
| function githubUser(array $overrides = []): MockResponse | ||
| { | ||
| return MockResponse::make([ | ||
| 'id' => 48_625_433, | ||
| 'login' => 'gvieira18', | ||
| 'name' => 'Gabriel Vieira', | ||
| 'email' => null, | ||
| 'avatar_url' => 'https://avatars.githubusercontent.com/u/48625433', | ||
| ...$overrides, | ||
| ]); | ||
| } | ||
|
|
||
| test('uses the public /user email when GitHub exposes one', function (): void { | ||
| $user = githubOAuthClient([ | ||
| GetCurrentUser::class => githubUser(['email' => 'public@example.com']), | ||
| ])->getAuthenticatedUser(GitHubOAuthAccessDTO::make(['access_token' => 'tok'])); | ||
|
|
||
| expect($user->email)->toBe('public@example.com') | ||
| ->and($user->provider)->toBe(IdentityProvider::GitHub) | ||
| ->and($user->providerId)->toBe('48625433'); | ||
| }); | ||
|
|
||
| test('falls back to the primary verified email when /user email is private', function (): void { | ||
| $user = githubOAuthClient([ | ||
| GetCurrentUser::class => githubUser(['email' => null]), | ||
| GetUserEmails::class => MockResponse::make([ | ||
| ['email' => 'secondary@example.com', 'primary' => false, 'verified' => true], | ||
| ['email' => 'primary@example.com', 'primary' => true, 'verified' => true], | ||
| ['email' => 'unverified@example.com', 'primary' => false, 'verified' => false], | ||
| ]), | ||
| ])->getAuthenticatedUser(GitHubOAuthAccessDTO::make(['access_token' => 'tok'])); | ||
|
|
||
| expect($user->email)->toBe('primary@example.com'); | ||
| }); | ||
|
|
||
| test('hard-fails when no email is primary', function (): void { | ||
| // Several verified addresses (work, school, noreply) but none primary — | ||
| // none can be picked, so login must abort instead of forking a duplicate. | ||
| expect(fn () => githubOAuthClient([ | ||
| GetCurrentUser::class => githubUser(['email' => null]), | ||
| GetUserEmails::class => MockResponse::make([ | ||
| ['email' => 'noreply@example.com', 'primary' => false, 'verified' => true], | ||
| ['email' => 'school@example.com', 'primary' => false, 'verified' => true], | ||
| ]), | ||
| ])->getAuthenticatedUser(GitHubOAuthAccessDTO::make(['access_token' => 'tok']))) | ||
| ->toThrow(OAuthFlowException::class); | ||
| }); | ||
|
|
||
| test('hard-fails when the primary email is not verified', function (): void { | ||
| expect(fn () => githubOAuthClient([ | ||
| GetCurrentUser::class => githubUser(['email' => null]), | ||
| GetUserEmails::class => MockResponse::make([ | ||
| ['email' => 'primary-unverified@example.com', 'primary' => true, 'verified' => false], | ||
| ['email' => 'verified@example.com', 'primary' => false, 'verified' => true], | ||
| ]), | ||
| ])->getAuthenticatedUser(GitHubOAuthAccessDTO::make(['access_token' => 'tok']))) | ||
| ->toThrow(OAuthFlowException::class); | ||
| }); | ||
|
|
||
| test('hard-fails when /user/emails is empty', function (): void { | ||
| expect(fn () => githubOAuthClient([ | ||
| GetCurrentUser::class => githubUser(['email' => null]), | ||
| GetUserEmails::class => MockResponse::make([]), | ||
| ])->getAuthenticatedUser(GitHubOAuthAccessDTO::make(['access_token' => 'tok']))) | ||
| ->toThrow(OAuthFlowException::class); | ||
| }); | ||
|
gvieira18 marked this conversation as resolved.
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.