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
20 changes: 18 additions & 2 deletions src/CloudApi/CloudCredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public function getBaseUri(): ?string
if ($uri = getenv('ACLI_CLOUD_API_BASE_URI')) {
return $uri;
}
return null;
return ($this->getActiveKeyData() ?? [])['cloud_api_base_uri'] ?? null;
}

/**
Expand All @@ -104,6 +104,22 @@ public function getAccountsUri(): ?string
if ($uri = getenv('ACLI_CLOUD_API_ACCOUNTS_URI')) {
return $uri;
}
return null;
return ($this->getActiveKeyData() ?? [])['accounts_uri'] ?? null;
}

/**
* @return array<string, mixed>|null
*/
private function getActiveKeyData(): ?array
{
$activeKey = $this->datastoreCloud->get('acli_key');
if (!$activeKey) {
return null;
}
$keys = $this->datastoreCloud->get('keys');
if (!is_array($keys) || !array_key_exists($activeKey, $keys)) {
return null;
}
return $keys[$activeKey];
}
}
55 changes: 45 additions & 10 deletions src/Command/Auth/AuthLoginCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Acquia\Cli\Command\Auth;

use Acquia\Cli\Command\CommandBase;
use Acquia\Cli\Exception\AcquiaCliException;
use AcquiaCloudApi\Endpoints\Account;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
Expand All @@ -20,11 +21,15 @@ protected function configure(): void
$this
->addOption('key', 'k', InputOption::VALUE_REQUIRED, 'Your Cloud Platform API key')
->addOption('secret', 's', InputOption::VALUE_REQUIRED, 'Your Cloud Platform API secret')
->addOption('environment', null, InputOption::VALUE_REQUIRED, 'Cloud Platform API environment', 'prod')

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm open to making this parameter completely hidden (if that's possible), or changing the language so there's no confusion between Cloud API environments (aka realms) and Cloud environments.

->setHelp('Acquia CLI can store multiple sets of credentials in case you have multiple Cloud Platform accounts. However, only a single account can be active at a time. This command allows you to activate a new or existing set of credentials.');
}

protected function execute(InputInterface $input, OutputInterface $output): int
{
$env = $input->getOption('environment');
[$baseUri, $accountsUri] = $this->getUrisForEnvironment($env);

$keys = $this->datastoreCloud->get('keys');
$activeKey = $this->datastoreCloud->get('acli_key');
if ($activeKey) {
Expand All @@ -34,16 +39,21 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$output->writeln('No Cloud Platform API key is active');
}

// If keys already are saved locally, prompt to select.
if ($keys && $input->isInteractive()) {
foreach ($keys as $uuid => $key) {
$keys[$uuid]['uuid'] = $uuid;
$matchingKeys = array_filter(
$keys ?? [],
static fn(array $keyData) => ($keyData['cloud_api_base_uri'] ?? null) === $baseUri,
);

// If keys already are saved locally for this environment, prompt to select.
if ($matchingKeys && $input->isInteractive()) {
foreach ($matchingKeys as $uuid => $key) {
$matchingKeys[$uuid]['uuid'] = $uuid;
}
$keys['create_new'] = [
$matchingKeys['create_new'] = [
'label' => 'Enter a new API key',
'uuid' => 'create_new',
];
$selectedKey = $this->promptChooseFromObjectsOrArrays($keys, 'uuid', 'label', 'Activate a Cloud Platform API key');
$selectedKey = $this->promptChooseFromObjectsOrArrays($matchingKeys, 'uuid', 'label', 'Activate a Cloud Platform API key');
if ($selectedKey['uuid'] !== 'create_new') {
$this->datastoreCloud->set('acli_key', $selectedKey['uuid']);
$output->writeln("<info>Acquia CLI will use the API key <options=bold>{$selectedKey['label']}</></info>");
Expand All @@ -55,23 +65,48 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$this->promptOpenBrowserToCreateToken($input);
$apiKey = $this->determineApiKey();
$apiSecret = $this->determineApiSecret();
$this->reAuthenticate($apiKey, $apiSecret, $this->cloudCredentials->getBaseUri(), $this->cloudCredentials->getAccountsUri());
$this->writeApiCredentialsToDisk($apiKey, $apiSecret);
$this->reAuthenticate($apiKey, $apiSecret, $baseUri, $accountsUri);
$this->writeApiCredentialsToDisk($apiKey, $apiSecret, $baseUri, $accountsUri);
$output->writeln("<info>Saved credentials</info>");

return Command::SUCCESS;
}

private function writeApiCredentialsToDisk(string $apiKey, string $apiSecret): void
/**
* @return array{?string, ?string}
*/
private function getUrisForEnvironment(string $env): array
{
$env = strtolower(trim($env));
if ($env === '' || $env === 'prod') {
return [null, null];
}
if (!preg_match('/^[a-z0-9-]+$/', $env)) {
throw new AcquiaCliException('Invalid environment value: {env}', ['env' => $env]);
}
return [
"https://$env.cloud.acquia.com/api",
"https://$env.accounts.acquia.com/api/auth/oauth/token",
];
}

private function writeApiCredentialsToDisk(string $apiKey, string $apiSecret, ?string $baseUri = null, ?string $accountsUri = null): void
{
$account = new Account($this->cloudApiClientService->getClient());
$accountInfo = $account->get();
$keys = $this->datastoreCloud->get('keys');
$keys[$apiKey] = [
$keyData = [
'label' => $accountInfo->mail,
'secret' => $apiSecret,
'uuid' => $apiKey,
];
if ($baseUri !== null) {
$keyData['cloud_api_base_uri'] = $baseUri;
}
if ($accountsUri !== null) {
$keyData['accounts_uri'] = $accountsUri;
}
$keys[$apiKey] = $keyData;
$this->datastoreCloud->set('keys', $keys);
$this->datastoreCloud->set('acli_key', $apiKey);
}
Expand Down
2 changes: 2 additions & 0 deletions src/Config/CloudDataConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ public function getConfigTreeBuilder(): TreeBuilder
->scalarNode('label')->end()
->scalarNode('uuid')->end()
->scalarNode('secret')->isRequired()->end()
->scalarNode('cloud_api_base_uri')->defaultNull()->end()
->scalarNode('accounts_uri')->defaultNull()->end()
->end()
->end()
->end()
Expand Down
72 changes: 72 additions & 0 deletions tests/phpunit/src/CloudApi/CloudCredentialsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

declare(strict_types=1);

namespace Acquia\Cli\Tests\CloudApi;

use Acquia\Cli\Tests\TestBase;

class CloudCredentialsTest extends TestBase
{
public function testGetBaseUriReturnsNullWhenNoStoredUri(): void
{
$this->assertNull($this->cloudCredentials->getBaseUri());
$this->assertNull($this->cloudCredentials->getAccountsUri());
}

public function testGetBaseUriReturnsStoredUriWhenNoEnvVar(): void
{
$this->datastoreCloud->set('keys', [
self::$key => [
'accounts_uri' => 'https://staging.accounts.acquia.com/api/auth/oauth/token',
'cloud_api_base_uri' => 'https://staging.cloud.acquia.com/api',
'label' => 'Test Key',
'secret' => self::$secret,
'uuid' => self::$key,
],
]);

$this->assertSame('https://staging.cloud.acquia.com/api', $this->cloudCredentials->getBaseUri());
$this->assertSame('https://staging.accounts.acquia.com/api/auth/oauth/token', $this->cloudCredentials->getAccountsUri());
}

public function testGetBaseUriReturnsNullWhenActiveKeyNotInKeysArray(): void
{
$this->datastoreCloud->set('keys', [
self::$key => [
'accounts_uri' => 'https://staging.accounts.acquia.com/api/auth/oauth/token',
'cloud_api_base_uri' => 'https://staging.cloud.acquia.com/api',
'label' => 'Test Key',
'secret' => self::$secret,
'uuid' => self::$key,
],
]);
$this->datastoreCloud->set('acli_key', 'nonexistent-key-uuid');

$this->assertNull($this->cloudCredentials->getBaseUri());
$this->assertNull($this->cloudCredentials->getAccountsUri());
}

public function testGetBaseUriEnvVarTakesPriorityOverStoredUri(): void
{
$this->datastoreCloud->set('keys', [
self::$key => [
'accounts_uri' => 'https://staging.accounts.acquia.com/api/auth/oauth/token',
'cloud_api_base_uri' => 'https://staging.cloud.acquia.com/api',
'label' => 'Test Key',
'secret' => self::$secret,
'uuid' => self::$key,
],
]);
putenv('ACLI_CLOUD_API_BASE_URI=https://qa.cloud.acquia.com/api');
putenv('ACLI_CLOUD_API_ACCOUNTS_URI=https://qa.accounts.acquia.com/api/auth/oauth/token');

try {
$this->assertSame('https://qa.cloud.acquia.com/api', $this->cloudCredentials->getBaseUri());
$this->assertSame('https://qa.accounts.acquia.com/api/auth/oauth/token', $this->cloudCredentials->getAccountsUri());
} finally {
putenv('ACLI_CLOUD_API_BASE_URI');
putenv('ACLI_CLOUD_API_ACCOUNTS_URI');
}
}
}
Loading