Skip to content
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

Create abstraction for oauth client registry #397

Merged
merged 1 commit into from
Jan 29, 2021
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
15 changes: 9 additions & 6 deletions src/Entity/User/OAuthToken.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@
namespace Buddy\Repman\Entity\User;

use Buddy\Repman\Entity\User;
use Buddy\Repman\Service\User\UserOAuthTokenRefresher;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\UniqueConstraint;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use League\OAuth2\Client\Grant\RefreshToken;
use Ramsey\Uuid\UuidInterface;

/**
Expand Down Expand Up @@ -88,13 +87,17 @@ public function isType(string $type): bool
return $this->type() === $type;
}

public function accessToken(ClientRegistry $oauth): string
public function accessToken(UserOAuthTokenRefresher $tokenRefresher): string
{
if ($this->expiresAt !== null && (new \DateTimeImmutable()) > $this->expiresAt->modify('-1 min')) {
if ($this->refreshToken === null) {
throw new \LogicException('Unable to refresh access token without refresh token');
}

try {
$newToken = $oauth->getClient($this->type)->getOAuth2Provider()->getAccessToken(new RefreshToken(), ['refresh_token' => $this->refreshToken]);
$this->accessToken = $newToken->getToken();
$this->expiresAt = $newToken->getExpires() !== null ? (new \DateTimeImmutable())->setTimestamp($newToken->getExpires()) : null;
$newToken = $tokenRefresher->refresh($this->type, $this->refreshToken);
$this->accessToken = $newToken->token();
$this->expiresAt = $newToken->expiresAt();
} catch (\Throwable $exception) {
throw new \RuntimeException('An error occurred while refreshing the access token: '.$exception->getMessage());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

use Buddy\Repman\Repository\PackageRepository;
use Buddy\Repman\Service\IntegrationRegister;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use Buddy\Repman\Service\User\UserOAuthTokenRefresher;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

Expand All @@ -15,13 +15,13 @@ abstract class AbstractHookHandler implements MessageHandlerInterface
protected PackageRepository $packages;
protected IntegrationRegister $integrations;
protected UrlGeneratorInterface $router;
protected ClientRegistry $oauth;
protected UserOAuthTokenRefresher $tokenRefresher;

public function __construct(PackageRepository $packages, IntegrationRegister $integrations, UrlGeneratorInterface $router, ClientRegistry $oauth)
public function __construct(PackageRepository $packages, IntegrationRegister $integrations, UrlGeneratorInterface $router, UserOAuthTokenRefresher $tokenRefresher)
{
$this->packages = $packages;
$this->integrations = $integrations;
$this->router = $router;
$this->oauth = $oauth;
$this->tokenRefresher = $tokenRefresher;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public function __invoke(AddBitbucketHook $message): void

try {
$this->integrations->bitbucketApi()->addHook(
$package->oauthToken()->accessToken($this->oauth),
$package->oauthToken()->accessToken($this->tokenRefresher),
$package->metadata(Metadata::BITBUCKET_REPO_NAME),
$this->router->generate('package_webhook', ['package' => $package->id()->toString()], UrlGeneratorInterface::ABSOLUTE_URL)
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public function __invoke(AddGitHubHook $message): void

try {
$this->integrations->gitHubApi()->addHook(
$package->oauthToken()->accessToken($this->oauth),
$package->oauthToken()->accessToken($this->tokenRefresher),
$package->metadata(Metadata::GITHUB_REPO_NAME),
$this->router->generate('package_webhook', ['package' => $package->id()->toString()], UrlGeneratorInterface::ABSOLUTE_URL)
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public function __invoke(AddGitLabHook $message): void

try {
$this->integrations->gitLabApi()->addHook(
$package->oauthToken()->accessToken($this->oauth),
$package->oauthToken()->accessToken($this->tokenRefresher),
$package->metadata(Metadata::GITLAB_PROJECT_ID),
$this->router->generate('package_webhook', ['package' => $package->id()->toString()], UrlGeneratorInterface::ABSOLUTE_URL)
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public function __invoke(RemoveBitbucketHook $message): void
{
$package = $this->packages->getById(Uuid::fromString($message->packageId()));
$this->integrations->bitbucketApi()->removeHook(
$package->oauthToken()->accessToken($this->oauth),
$package->oauthToken()->accessToken($this->tokenRefresher),
$package->metadata(Metadata::BITBUCKET_REPO_NAME),
$this->router->generate('package_webhook', ['package' => $package->id()->toString()], UrlGeneratorInterface::ABSOLUTE_URL)
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public function __invoke(RemoveGitHubHook $message): void
$package = $this->packages->getById(Uuid::fromString($message->packageId()));

$this->integrations->gitHubApi()->removeHook(
$package->oauthToken()->accessToken($this->oauth),
$package->oauthToken()->accessToken($this->tokenRefresher),
$package->metadata(Metadata::GITHUB_REPO_NAME),
$this->router->generate('package_webhook', ['package' => $package->id()->toString()], UrlGeneratorInterface::ABSOLUTE_URL)
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public function __invoke(RemoveGitLabHook $message): void
{
$package = $this->packages->getById(Uuid::fromString($message->packageId()));
$this->integrations->gitLabApi()->removeHook(
$package->oauthToken()->accessToken($this->oauth),
$package->oauthToken()->accessToken($this->tokenRefresher),
$package->metadata(Metadata::GITLAB_PROJECT_ID),
$this->router->generate('package_webhook', ['package' => $package->id()->toString()], UrlGeneratorInterface::ABSOLUTE_URL)
);
Expand Down
10 changes: 5 additions & 5 deletions src/Service/PackageSynchronizer/ComposerPackageSynchronizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Buddy\Repman\Service\PackageNormalizer;
use Buddy\Repman\Service\PackageSynchronizer;
use Buddy\Repman\Service\ReadmeExtractor;
use Buddy\Repman\Service\User\UserOAuthTokenRefresher;
use Composer\Config;
use Composer\Factory;
use Composer\IO\BufferIO;
Expand All @@ -22,7 +23,6 @@
use Composer\Repository\RepositoryFactory;
use Composer\Repository\RepositoryInterface;
use Composer\Semver\Comparator;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use Ramsey\Uuid\Uuid;
use Symfony\Component\Console\Output\OutputInterface;

Expand All @@ -33,22 +33,22 @@ final class ComposerPackageSynchronizer implements PackageSynchronizer
private PackageRepository $packageRepository;
private Storage $distStorage;
private ReadmeExtractor $readmeExtractor;
private ClientRegistry $oauth;
private UserOAuthTokenRefresher $tokenRefresher;
private string $gitlabUrl;

public function __construct(
PackageManager $packageManager,
PackageNormalizer $packageNormalizer,
PackageRepository $packageRepository,
Storage $distStorage,
ClientRegistry $oauth,
UserOAuthTokenRefresher $tokenRefresher,
string $gitlabUrl
) {
$this->packageManager = $packageManager;
$this->packageNormalizer = $packageNormalizer;
$this->packageRepository = $packageRepository;
$this->distStorage = $distStorage;
$this->oauth = $oauth;
$this->tokenRefresher = $tokenRefresher;
$this->gitlabUrl = $gitlabUrl;
$this->readmeExtractor = new ReadmeExtractor($this->distStorage);
}
Expand Down Expand Up @@ -215,7 +215,7 @@ private function createIO(Package $package): BufferIO

private function accessToken(Package $package): string
{
return $package->oauthToken()->accessToken($this->oauth);
return $package->oauthToken()->accessToken($this->tokenRefresher);
}

private function createConfig(Package $package, IOInterface $io): Config
Expand Down
4 changes: 4 additions & 0 deletions src/Service/Proxy.php
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,10 @@ public function download(string $package, string $version): void

foreach ($this->decodeMetadata($package) as $packageData) {
$lastDist = $packageData['dist'] ?? $lastDist;
if (!isset($lastDist['reference']) || !isset($lastDist['type']) || !isset($lastDist['url'])) {
continue;
}

$path = $this->distPath($package, $lastDist['reference'], $lastDist['type']);
if ($version === $packageData['version'] && !$this->filesystem->has($path)) {
$this->filesystem->writeStream($path, $this->downloader->getContents($lastDist['url'])
Expand Down
9 changes: 4 additions & 5 deletions src/Service/User/UserOAuthTokenProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,19 @@

use Buddy\Repman\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use Ramsey\Uuid\Uuid;

class UserOAuthTokenProvider
{
private UserRepository $repository;
private EntityManagerInterface $em;
private ClientRegistry $oauth;
private UserOAuthTokenRefresher $tokenRefresher;

public function __construct(UserRepository $repository, EntityManagerInterface $em, ClientRegistry $oauth)
public function __construct(UserRepository $repository, EntityManagerInterface $em, UserOAuthTokenRefresher $tokenRefresher)
{
$this->repository = $repository;
$this->em = $em;
$this->oauth = $oauth;
$this->tokenRefresher = $tokenRefresher;
}

public function findAccessToken(string $userId, string $type): ?string
Expand All @@ -29,7 +28,7 @@ public function findAccessToken(string $userId, string $type): ?string
return null;
}

$accessToken = $token->accessToken($this->oauth);
$accessToken = $token->accessToken($this->tokenRefresher);
$this->em->flush();

return $accessToken;
Expand Down
30 changes: 30 additions & 0 deletions src/Service/User/UserOAuthTokenRefresher.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

namespace Buddy\Repman\Service\User;

use Buddy\Repman\Service\User\UserOAuthTokenRefresher\AccessToken;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use League\OAuth2\Client\Grant\RefreshToken;

class UserOAuthTokenRefresher
{
private ClientRegistry $oauth;

public function __construct(ClientRegistry $oauth)
{
$this->oauth = $oauth;
}

public function refresh(string $type, string $refreshToken): AccessToken
{
$accessToken = $this->oauth->getClient($type)->getOAuth2Provider()
->getAccessToken(new RefreshToken(), ['refresh_token' => $refreshToken]);

return new AccessToken(
$accessToken->getToken(),
$accessToken->getExpires() !== null ? (new \DateTimeImmutable())->setTimestamp($accessToken->getExpires()) : null
);
}
}
28 changes: 28 additions & 0 deletions src/Service/User/UserOAuthTokenRefresher/AccessToken.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Buddy\Repman\Service\User\UserOAuthTokenRefresher;

class AccessToken
{
private string $token;

private ?\DateTimeImmutable $expiresAt;

public function __construct(string $token, ?\DateTimeImmutable $expiresAt = null)
{
$this->token = $token;
$this->expiresAt = $expiresAt;
}

public function token(): string
{
return $this->token;
}

public function expiresAt(): ?\DateTimeImmutable
{
return $this->expiresAt;
}
}
4 changes: 2 additions & 2 deletions tests/MotherObject/OAuthTokenMother.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@

final class OAuthTokenMother
{
public static function withoutRefreshToken(): OAuthToken
public static function withoutRefreshToken(?\DateTimeImmutable $expireAt = null): OAuthToken
{
return new OAuthToken(Uuid::uuid4(), self::user(), OAuthToken::TYPE_GITHUB, 'token');
return new OAuthToken(Uuid::uuid4(), self::user(), OAuthToken::TYPE_GITHUB, 'token', null, $expireAt);
}

public static function withExpireTime(\DateTimeImmutable $expireAt): OAuthToken
Expand Down
40 changes: 19 additions & 21 deletions tests/Unit/Entity/User/OAuthTokenTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,22 @@

namespace Buddy\Repman\Tests\Unit\Entity\User;

use Buddy\Repman\Service\User\UserOAuthTokenRefresher;
use Buddy\Repman\Service\User\UserOAuthTokenRefresher\AccessToken;
use Buddy\Repman\Tests\MotherObject\OAuthTokenMother;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use KnpU\OAuth2ClientBundle\Client\OAuth2ClientInterface;
use League\OAuth2\Client\Provider\AbstractProvider;
use League\OAuth2\Client\Token\AccessToken;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;

final class OAuthTokenTest extends TestCase
{
/**
* @var ClientRegistry|MockObject
* @var UserOAuthTokenRefresher|MockObject
*/
private $oauth;

/**
* @var AbstractProvider|MockObject
*/
private $provider;
private $refresher;

protected function setUp(): void
{
$this->oauth = $this->createMock(ClientRegistry::class);
$this->provider = $this->createMock(AbstractProvider::class);
$client = $this->createMock(OAuth2ClientInterface::class);
$client->method('getOAuth2Provider')->willReturn($this->provider);
$this->oauth->method('getClient')->willReturn($client);
$this->refresher = $this->createMock(UserOAuthTokenRefresher::class);
}

/**
Expand All @@ -39,27 +28,36 @@ protected function setUp(): void
public function testExpiredAccessToken(string $modifyTime): void
{
$token = OAuthTokenMother::withExpireTime((new \DateTimeImmutable())->modify($modifyTime));
$this->provider->method('getAccessToken')->willReturn(new AccessToken(['access_token' => 'new-token']));
$this->refresher->method('refresh')->willReturn(new AccessToken('new-token'));

self::assertEquals('new-token', $token->accessToken($this->oauth));
self::assertEquals('new-token', $token->accessToken($this->refresher));
}

public function testAccessTokenWithFutureExpirationDate(): void
{
$token = OAuthTokenMother::withExpireTime((new \DateTimeImmutable())->modify('61 sec'));

self::assertEquals('token', $token->accessToken($this->oauth));
self::assertEquals('token', $token->accessToken($this->refresher));
}

public function testErrorDuringRefresh(): void
{
$token = OAuthTokenMother::withExpireTime((new \DateTimeImmutable())->modify('-1 day'));
$this->provider->method('getAccessToken')->willThrowException(new \RuntimeException('invalid refresh_token'));
$this->refresher->method('refresh')->willThrowException(new \RuntimeException('invalid refresh_token'));

$this->expectException(\RuntimeException::class);
$this->expectExceptionMessageMatches('/invalid refresh_token/');

$token->accessToken($this->oauth);
$token->accessToken($this->refresher);
}

public function testErrorWhenMissingRefreshToken(): void
{
$token = OAuthTokenMother::withoutRefreshToken((new \DateTimeImmutable())->modify('-1 day'));

$this->expectException(\LogicException::class);

$token->accessToken($this->refresher);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
use Buddy\Repman\Service\Organization\PackageManager;
use Buddy\Repman\Service\PackageNormalizer;
use Buddy\Repman\Service\PackageSynchronizer\ComposerPackageSynchronizer;
use Buddy\Repman\Service\User\UserOAuthTokenRefresher;
use Buddy\Repman\Tests\Doubles\FakeDownloader;
use Buddy\Repman\Tests\MotherObject\PackageMother;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
use PHPUnit\Framework\MockObject\MockObject;
Expand All @@ -38,7 +38,7 @@ protected function setUp(): void
new PackageNormalizer(),
$this->repoMock = $this->createMock(PackageRepository::class),
$distStorage,
$this->createMock(ClientRegistry::class),
$this->createMock(UserOAuthTokenRefresher::class),
'gitlab.com'
);
$this->resourcesDir = dirname(__DIR__, 3).'/Resources/';
Expand Down
Loading