refactor: provider authentication flow

This commit is contained in:
Vincent 2024-09-30 13:48:15 +02:00
parent b162f2313e
commit 81512bebb4
No known key found for this signature in database
GPG Key ID: 056662E78D70E358
7 changed files with 98 additions and 78 deletions

View File

@ -3,7 +3,7 @@
namespace App\Config; namespace App\Config;
use App\Service\Connector\GandiProvider; use App\Service\Connector\GandiProvider;
use App\Service\Connector\NamecheapConnector; use App\Service\Connector\NamecheapProvider;
use App\Service\Connector\OvhProvider; use App\Service\Connector\OvhProvider;
enum ConnectorProvider: string enum ConnectorProvider: string
@ -17,7 +17,7 @@ enum ConnectorProvider: string
return match ($this) { return match ($this) {
ConnectorProvider::OVH => OvhProvider::class, ConnectorProvider::OVH => OvhProvider::class,
ConnectorProvider::GANDI => GandiProvider::class, ConnectorProvider::GANDI => GandiProvider::class,
ConnectorProvider::NAMECHEAP => NamecheapConnector::class, ConnectorProvider::NAMECHEAP => NamecheapProvider::class,
}; };
} }
} }

View File

@ -9,6 +9,8 @@ use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Attribute\Route; use Symfony\Component\Routing\Attribute\Route;
@ -20,7 +22,9 @@ class ConnectorController extends AbstractController
public function __construct( public function __construct(
private readonly SerializerInterface $serializer, private readonly SerializerInterface $serializer,
private readonly EntityManagerInterface $em, private readonly EntityManagerInterface $em,
private readonly LoggerInterface $logger private readonly LoggerInterface $logger,
#[Autowire(service: 'service_container')]
private ContainerInterface $locator
) { ) {
} }
@ -71,10 +75,9 @@ class ConnectorController extends AbstractController
throw new BadRequestHttpException('Provider not found'); throw new BadRequestHttpException('Provider not found');
} }
/** @var AbstractProvider $connectorProviderClass */ /** @var AbstractProvider $providerClient */
$connectorProviderClass = $provider->getConnectorProvider(); $providerClient = $this->locator->get($provider->getConnectorProvider());
$authData = $providerClient->verifyAuthData($connector->getAuthData());
$authData = $connectorProviderClass::verifyAuthData($connector->getAuthData(), $client);
$connector->setAuthData($authData); $connector->setAuthData($authData);
$this->logger->info('User {username} authentication data with the {provider} provider has been validated.', [ $this->logger->info('User {username} authentication data with the {provider} provider has been validated.', [

View File

@ -41,7 +41,6 @@ use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Attribute\Route; use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Serializer\SerializerInterface; use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class WatchListController extends AbstractController class WatchListController extends AbstractController
{ {
@ -50,7 +49,6 @@ class WatchListController extends AbstractController
private readonly EntityManagerInterface $em, private readonly EntityManagerInterface $em,
private readonly WatchListRepository $watchListRepository, private readonly WatchListRepository $watchListRepository,
private readonly LoggerInterface $logger, private readonly LoggerInterface $logger,
private readonly HttpClientInterface $httpClient,
private readonly ChatNotificationService $chatNotificationService, private readonly ChatNotificationService $chatNotificationService,
#[Autowire(service: 'service_container')] #[Autowire(service: 'service_container')]
private ContainerInterface $locator private ContainerInterface $locator
@ -184,7 +182,6 @@ class WatchListController extends AbstractController
/** @var AbstractProvider $connectorProvider */ /** @var AbstractProvider $connectorProvider */
$connectorProvider = $this->locator->get($connectorProviderClass); $connectorProvider = $this->locator->get($connectorProviderClass);
$connectorProvider::verifyAuthData($connector->getAuthData(), $this->httpClient); // We want to check if the tokens are OK
$connectorProvider->authenticate($connector->getAuthData()); $connectorProvider->authenticate($connector->getAuthData());
$supported = $connectorProvider->isSupported(...$watchList->getDomains()->toArray()); $supported = $connectorProvider->isSupported(...$watchList->getDomains()->toArray());

View File

@ -5,8 +5,14 @@ namespace App\Service\Connector;
use App\Entity\Domain; use App\Entity\Domain;
use Psr\Cache\CacheItemInterface; use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface; use Psr\Cache\CacheItemPoolInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
* The typical flow of a provider will go as follows:
*
* MyProvider $provider; // gotten from DI
* $provider->authenticate($authData);
* $provider->orderDomain($domain, $dryRun);
*/
abstract class AbstractProvider abstract class AbstractProvider
{ {
protected array $authData; protected array $authData;
@ -16,7 +22,17 @@ abstract class AbstractProvider
) { ) {
} }
abstract public static function verifyAuthData(array $authData, HttpClientInterface $client): array; /**
* @param array $authData raw authentication data as supplied by the user
*
* @return array a cleaned up version of the authentication data
*/
abstract public function verifyAuthData(array $authData): array;
/**
* @throws \Exception when the registrar denies the authentication
*/
abstract public function assertAuthentication(): void; // TODO use dedicated exception type
abstract public function orderDomain(Domain $domain, bool $dryRun): void; abstract public function orderDomain(Domain $domain, bool $dryRun): void;
@ -53,9 +69,13 @@ abstract class AbstractProvider
return true; return true;
} }
/**
* @throws \Exception
*/
public function authenticate(array $authData): void public function authenticate(array $authData): void
{ {
$this->authData = $authData; $this->authData = $this->verifyAuthData($authData);
$this->assertAuthentication();
} }
abstract protected function getCachedTldList(): CacheItemInterface; abstract protected function getCachedTldList(): CacheItemInterface;

View File

@ -43,17 +43,15 @@ class GandiProvider extends AbstractProvider
throw new \InvalidArgumentException('Domain name cannot be null'); throw new \InvalidArgumentException('Domain name cannot be null');
} }
$authData = self::verifyAuthData($this->authData, $this->client);
$user = $this->client->request('GET', '/v5/organization/user-info', (new HttpOptions()) $user = $this->client->request('GET', '/v5/organization/user-info', (new HttpOptions())
->setAuthBearer($authData['token']) ->setAuthBearer($this->authData['token'])
->setHeader('Accept', 'application/json') ->setHeader('Accept', 'application/json')
->setBaseUri(self::BASE_URL) ->setBaseUri(self::BASE_URL)
->toArray() ->toArray()
)->toArray(); )->toArray();
$httpOptions = (new HttpOptions()) $httpOptions = (new HttpOptions())
->setAuthBearer($authData['token']) ->setAuthBearer($this->authData['token'])
->setHeader('Accept', 'application/json') ->setHeader('Accept', 'application/json')
->setBaseUri(self::BASE_URL) ->setBaseUri(self::BASE_URL)
->setHeader('Dry-Run', $dryRun ? '1' : '0') ->setHeader('Dry-Run', $dryRun ? '1' : '0')
@ -74,9 +72,9 @@ class GandiProvider extends AbstractProvider
'tld_period' => 'golive', 'tld_period' => 'golive',
]); ]);
if (array_key_exists('sharingId', $authData)) { if (array_key_exists('sharingId', $this->authData)) {
$httpOptions->setQuery([ $httpOptions->setQuery([
'sharing_id' => $authData['sharingId'], 'sharing_id' => $this->authData['sharingId'],
]); ]);
} }
@ -91,7 +89,7 @@ class GandiProvider extends AbstractProvider
/** /**
* @throws TransportExceptionInterface * @throws TransportExceptionInterface
*/ */
public static function verifyAuthData(array $authData, HttpClientInterface $client): array public function verifyAuthData(array $authData): array
{ {
$token = $authData['token']; $token = $authData['token'];
@ -111,17 +109,6 @@ class GandiProvider extends AbstractProvider
throw new HttpException(451, 'The user has not given explicit consent'); throw new HttpException(451, 'The user has not given explicit consent');
} }
$response = $client->request('GET', '/v5/organization/user-info', (new HttpOptions())
->setAuthBearer($token)
->setHeader('Accept', 'application/json')
->setBaseUri(self::BASE_URL)
->toArray()
);
if (Response::HTTP_OK !== $response->getStatusCode()) {
throw new BadRequestHttpException('The status of these credentials is not valid');
}
$authDataReturned = [ $authDataReturned = [
'token' => $token, 'token' => $token,
'acceptConditions' => $acceptConditions, 'acceptConditions' => $acceptConditions,
@ -136,6 +123,20 @@ class GandiProvider extends AbstractProvider
return $authDataReturned; return $authDataReturned;
} }
public function assertAuthentication(): void
{
$response = $this->client->request('GET', '/v5/organization/user-info', (new HttpOptions())
->setAuthBearer($this->authData['token'])
->setHeader('Accept', 'application/json')
->setBaseUri(self::BASE_URL)
->toArray()
);
if (Response::HTTP_OK !== $response->getStatusCode()) {
throw new BadRequestHttpException('The status of these credentials is not valid');
}
}
/** /**
* @throws TransportExceptionInterface * @throws TransportExceptionInterface
* @throws ServerExceptionInterface * @throws ServerExceptionInterface
@ -145,10 +146,8 @@ class GandiProvider extends AbstractProvider
*/ */
protected function getSupportedTldList(): array protected function getSupportedTldList(): array
{ {
$authData = self::verifyAuthData($this->authData, $this->client);
$response = $this->client->request('GET', '/v5/domain/tlds', (new HttpOptions()) $response = $this->client->request('GET', '/v5/domain/tlds', (new HttpOptions())
->setAuthBearer($authData['token']) ->setAuthBearer($this->authData['token'])
->setHeader('Accept', 'application/json') ->setHeader('Accept', 'application/json')
->setBaseUri(self::BASE_URL) ->setBaseUri(self::BASE_URL)
->toArray())->toArray(); ->toArray())->toArray();

View File

@ -9,7 +9,7 @@ use Symfony\Component\DependencyInjection\Attribute\Autoconfigure;
use Symfony\Contracts\HttpClient\HttpClientInterface; use Symfony\Contracts\HttpClient\HttpClientInterface;
#[Autoconfigure(public: true)] #[Autoconfigure(public: true)]
class NamecheapConnector extends AbstractProvider class NamecheapProvider extends AbstractProvider
{ {
public const BASE_URL = 'https://api.namecheap.com/xml.response'; public const BASE_URL = 'https://api.namecheap.com/xml.response';
@ -81,20 +81,21 @@ class NamecheapConnector extends AbstractProvider
return $data->CommandResponse; return $data->CommandResponse;
} }
public static function verifyAuthData(array $authData, HttpClientInterface $client): array public function verifyAuthData(array $authData): array
{ {
// TODO call gettldlist to introspect authentication
// need to make verifyAuthData local to do this properly...
return [ return [
'ApiUser' => $authData['ApiUser'], 'ApiUser' => $authData['ApiUser'],
'ApiKey' => $authData['ApiKey'], 'ApiKey' => $authData['ApiKey'],
'acceptConditions' => $authData['acceptConditions'], 'acceptConditions' => $authData['acceptConditions'],
'ownerLegalAge' => $authData['ownerLegalAge'], 'ownerLegalAge' => $authData['ownerLegalAge'],
'waiveRetractionPeriod' => $authData['waiveRetractionPeriod'],
]; ];
} }
public function assertAuthentication(): void
{
$this->call('namecheap.domains.gettldlist', [], false);
}
protected function getCachedTldList(): CacheItemInterface protected function getCachedTldList(): CacheItemInterface
{ {
return $this->cacheItemPool->getItem('app.provider.namecheap.supported-tld'); return $this->cacheItemPool->getItem('app.provider.namecheap.supported-tld');

View File

@ -7,10 +7,10 @@ use GuzzleHttp\Exception\ClientException;
use Ovh\Api; use Ovh\Api;
use Ovh\Exceptions\InvalidParameterException; use Ovh\Exceptions\InvalidParameterException;
use Psr\Cache\CacheItemInterface; use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\InvalidArgumentException; use Psr\Cache\InvalidArgumentException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class OvhProvider extends AbstractProvider class OvhProvider extends AbstractProvider
{ {
@ -41,8 +41,9 @@ class OvhProvider extends AbstractProvider
], ],
]; ];
public function __construct(private HttpClientInterface $client) public function __construct(CacheItemPoolInterface $cacheItemPool)
{ {
parent::__construct($cacheItemPool);
} }
/** /**
@ -61,21 +62,19 @@ class OvhProvider extends AbstractProvider
throw new \InvalidArgumentException('Domain name cannot be null'); throw new \InvalidArgumentException('Domain name cannot be null');
} }
$authData = self::verifyAuthData($this->authData, $this->client); $acceptConditions = $this->authData['acceptConditions'];
$ownerLegalAge = $this->authData['ownerLegalAge'];
$acceptConditions = $authData['acceptConditions']; $waiveRetractationPeriod = $this->authData['waiveRetractationPeriod'];
$ownerLegalAge = $authData['ownerLegalAge'];
$waiveRetractationPeriod = $authData['waiveRetractationPeriod'];
$conn = new Api( $conn = new Api(
$authData['appKey'], $this->authData['appKey'],
$authData['appSecret'], $this->authData['appSecret'],
$authData['apiEndpoint'], $this->authData['apiEndpoint'],
$authData['consumerKey'] $this->authData['consumerKey']
); );
$cart = $conn->post('/order/cart', [ $cart = $conn->post('/order/cart', [
'ovhSubsidiary' => $authData['ovhSubsidiary'], 'ovhSubsidiary' => $this->authData['ovhSubsidiary'],
'description' => 'Domain Watchdog', 'description' => 'Domain Watchdog',
]); ]);
$cartId = $cart['cartId']; $cartId = $cart['cartId'];
@ -85,8 +84,8 @@ class OvhProvider extends AbstractProvider
]); ]);
$pricingModes = ['create-default']; $pricingModes = ['create-default'];
if ('create-default' !== $authData['pricingMode']) { if ('create-default' !== $this->authData['pricingMode']) {
$pricingModes[] = $authData['pricingMode']; $pricingModes[] = $this->authData['pricingMode'];
} }
$offer = array_filter($offers, fn ($offer) => 'create' === $offer['action'] $offer = array_filter($offers, fn ($offer) => 'create' === $offer['action']
@ -135,7 +134,7 @@ class OvhProvider extends AbstractProvider
/** /**
* @throws \Exception * @throws \Exception
*/ */
public static function verifyAuthData(array $authData, HttpClientInterface $client): array public function verifyAuthData(array $authData): array
{ {
$appKey = $authData['appKey']; $appKey = $authData['appKey'];
$appSecret = $authData['appSecret']; $appSecret = $authData['appSecret'];
@ -164,11 +163,26 @@ class OvhProvider extends AbstractProvider
throw new HttpException(451, 'The user has not given explicit consent'); throw new HttpException(451, 'The user has not given explicit consent');
} }
return [
'appKey' => $appKey,
'appSecret' => $appSecret,
'apiEndpoint' => $apiEndpoint,
'consumerKey' => $consumerKey,
'ovhSubsidiary' => $ovhSubsidiary,
'pricingMode' => $pricingMode,
'acceptConditions' => $acceptConditions,
'ownerLegalAge' => $ownerLegalAge,
'waiveRetractationPeriod' => $waiveRetractationPeriod,
];
}
public function assertAuthentication(): void
{
$conn = new Api( $conn = new Api(
$appKey, $this->authData['appKey'],
$appSecret, $this->authData['appSecret'],
$apiEndpoint, $this->authData['apiEndpoint'],
$consumerKey $this->authData['consumerKey'],
); );
try { try {
@ -201,18 +215,6 @@ class OvhProvider extends AbstractProvider
throw new BadRequestHttpException('This Connector does not have enough permissions on the Provider API. Please recreate this Connector.'); throw new BadRequestHttpException('This Connector does not have enough permissions on the Provider API. Please recreate this Connector.');
} }
} }
return [
'appKey' => $appKey,
'appSecret' => $appSecret,
'apiEndpoint' => $apiEndpoint,
'consumerKey' => $consumerKey,
'ovhSubsidiary' => $ovhSubsidiary,
'pricingMode' => $pricingMode,
'acceptConditions' => $acceptConditions,
'ownerLegalAge' => $ownerLegalAge,
'waiveRetractationPeriod' => $waiveRetractationPeriod,
];
} }
/** /**
@ -222,17 +224,15 @@ class OvhProvider extends AbstractProvider
*/ */
protected function getSupportedTldList(): array protected function getSupportedTldList(): array
{ {
$authData = self::verifyAuthData($this->authData, $this->client);
$conn = new Api( $conn = new Api(
$authData['appKey'], $this->authData['appKey'],
$authData['appSecret'], $this->authData['appSecret'],
$authData['apiEndpoint'], $this->authData['apiEndpoint'],
$authData['consumerKey'] $this->authData['consumerKey']
); );
return $conn->get('/domain/extensions', [ return $conn->get('/domain/extensions', [
'ovhSubsidiary' => $authData['ovhSubsidiary'], 'ovhSubsidiary' => $this->authData['ovhSubsidiary'],
]); ]);
} }