Skip to content

Commit

Permalink
Remove support for pre-"Auth" APIs
Browse files Browse the repository at this point in the history
  • Loading branch information
pjcdawkins committed Dec 15, 2023
1 parent dbc0e6c commit ccb7dec
Show file tree
Hide file tree
Showing 13 changed files with 39 additions and 121 deletions.
12 changes: 3 additions & 9 deletions config-defaults.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -263,16 +263,10 @@ api:
# though a recommendation will be displayed.
write_user_ssh_config: null

# Whether the Auth API is enabled.
auth: true

# Whether the API supports project invitations (requires "auth").
invitations: false

# Whether the Organizations API is enabled (requires "auth").
# Whether the Organizations API is enabled.
organizations: false

# Whether Centralized User Management is available (requires "auth" and "organizations").
# Whether Centralized User Management is available (requires "organizations").
centralized_permissions: false

# Whether the projects list should be fetched from the newer "extended-access" API instead of "/me".
Expand All @@ -283,7 +277,7 @@ api:
# This can be null for no filtering, or a string or a list of strings.
vendor_filter: null

# Whether the User Verification APIs (/me/verification and /users/ID/phonenumber) are enabled (requires "auth").
# Whether the User Verification APIs (/me/verification and /users/ID/phonenumber) are enabled.
user_verification: false

# Whether the Metrics API is enabled.
Expand Down
1 change: 0 additions & 1 deletion config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ api:

ssh_domain_wildcards: ['*.platform.sh']

invitations: true
organizations: true
centralized_permissions: true
user_verification: true
Expand Down
10 changes: 1 addition & 9 deletions src/Command/ApiCurlCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,6 @@ class ApiCurlCommand extends CommandBase
{
protected $hiddenInList = true;

public function isEnabled() {
if (!$this->config()->has('api.base_url')) {
return false;
}

return parent::isEnabled();
}

protected function configure()
{
$this->setName('api:curl')
Expand All @@ -27,7 +19,7 @@ protected function configure()

protected function execute(InputInterface $input, OutputInterface $output)
{
$url = $this->config()->get('api.base_url');
$url = $this->config()->getApiUrl();

// Initialize the API service so that it gets CommandBase's event listeners
// (allowing for auto login).
Expand Down
2 changes: 1 addition & 1 deletion src/Command/Auth/AuthInfoCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
}

// Exit early if it's the user ID.
if ($property === 'id' && $this->api()->authApiEnabled()) {
if ($property === 'id') {
$userId = $this->api()->getMyUserId($input->getOption('refresh'));
if ($userId === false) {
$this->stdErr->writeln('The current session is not associated with a user ID');
Expand Down
5 changes: 2 additions & 3 deletions src/Command/Auth/AuthTokenCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,11 @@ protected function configure()
. ' Take care not to expose the token in a shared program or system, or to send the token to the wrong API domain.'
);
$executable = $this->config()->get('application.executable');
$apiUrl = $this->config()->getApiUrl();
$examples = [
'Print the payload for JWT-formatted tokens' => \sprintf('%s auth:token -W | cut -d. -f2 | base64 -d', $executable),
'Use the token in a curl command' => \sprintf('curl -H"$(%s auth:token -HW)" %s/users/me', $executable, rtrim($apiUrl, '/')),
];
if ($apiUrl = $this->config()->getWithDefault('api.base_url', '')) {
$examples['Use the token in a curl command'] = \sprintf('curl -H"$(%s auth:token -HW)" %s/users/me', $executable, rtrim($apiUrl, '/'));
}
$help .= "\n\n<comment>Examples:</comment>";
foreach ($examples as $description => $example) {
$help .= "\n\n$description:\n <info>$example</info>";
Expand Down
5 changes: 1 addition & 4 deletions src/Command/Auth/VerifyPhoneNumberCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,7 @@ protected function configure()

public function isEnabled()
{
$config = $this->config();
if (!$config->getWithDefault('api.user_verification', false)
|| !$config->getWithDefault('api.auth', false)
|| !$config->getWithDefault('api.base_url', '')) {
if (!$this->config()->getWithDefault('api.user_verification', false)) {
return false;
}
return parent::isEnabled();
Expand Down
11 changes: 2 additions & 9 deletions src/Command/CommandBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -923,12 +923,7 @@ protected function addHiddenOption($name, $shortcut = null, $mode = null, $descr
protected function addProjectOption()
{
$this->addOption('project', 'p', InputOption::VALUE_REQUIRED, 'The project ID or URL');

if ($this->config()->getWithDefault('api.base_url', '') !== '') {
$this->addHiddenOption('host', null, InputOption::VALUE_REQUIRED, 'Deprecated option, no longer used');
} else {
$this->addOption('host', null, InputOption::VALUE_REQUIRED, "The project's API hostname");
}
$this->addHiddenOption('host', null, InputOption::VALUE_REQUIRED, 'Deprecated option, no longer used');

return $this;
}
Expand Down Expand Up @@ -1560,9 +1555,7 @@ final protected function validateInput(InputInterface $input, $envNotRequired =
$environmentId = null;

// Warn about using the deprecated --host option.
if ($this->config()->getWithDefault('api.base_url', '') !== '') {
$this->warnAboutDeprecatedOptions(['host']);
}
$this->warnAboutDeprecatedOptions(['host']);

// Identify the project.
if ($projectId !== null) {
Expand Down
11 changes: 4 additions & 7 deletions src/Command/Organization/OrganizationCreateCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,11 @@ private function getForm()
'options' => $countryList,
'asChoice' => false,
'defaultCallback' => function () use ($countryList) {
if ($this->api()->authApiEnabled()) {
$userCountry = $this->api()->getUser()->country;
if (isset($countryList[$userCountry])) {
return $countryList[$userCountry];
}
return $userCountry ?: null;
$userCountry = $this->api()->getUser()->country;
if (isset($countryList[$userCountry])) {
return $countryList[$userCountry];
}
return null;
return $userCountry ?: null;
},
'normalizer' => function ($value) { return $this->normalizeCountryCode($value); },
'validator' => function ($countryCode) use ($countryList) {
Expand Down
2 changes: 1 addition & 1 deletion src/Command/Organization/OrganizationCurlCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
{
$organization = $this->validateOrganizationInput($input);

$apiUrl = Url::fromString($this->config()->get('api.base_url'));
$apiUrl = Url::fromString($this->config()->getApiUrl());
$absoluteUrl = $apiUrl->combine($organization->getUri())->__toString();

/** @var CurlCli $curl */
Expand Down
15 changes: 3 additions & 12 deletions src/Command/User/UserAddCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,7 @@ protected function configure()

$this->addRoleOption();

if ($this->config()->getWithDefault('api.invitations', false)) {
$this->addOption('force-invite', null, InputOption::VALUE_NONE, 'Send an invitation, even if one has already been sent');
}
$this->addOption('force-invite', null, InputOption::VALUE_NONE, 'Send an invitation, even if one has already been sent');

$this->addProjectOption();
$this->addWaitOptions();
Expand Down Expand Up @@ -319,7 +317,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
$this->stdErr->writeln('');

// If the user does not already exist on the project, then use the Invitations API.
if (!$existingProjectAccess && $this->config()->getWithDefault('api.invitations', false)) {
if (!$existingProjectAccess) {
$this->stdErr->writeln('Inviting the user to the project...');
$permissions = [];
foreach ($desiredTypeRoles as $type => $role) {
Expand All @@ -343,14 +341,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
}

// Make the desired changes at the project level.
if (!$existingProjectAccess) {
$this->stdErr->writeln("Adding the user to the project");
$result = $project->addUser($email, $desiredProjectRole);
$activities = $result->getActivities();
/** @var ProjectAccess $projectAccess */
$projectAccess = $result->getEntity();
$userId = $projectAccess->id;
} elseif ($existingProjectAccess->role !== $desiredProjectRole) {
if ($existingProjectAccess->role !== $desiredProjectRole) {
$this->stdErr->writeln("Setting the user's project role to: $desiredProjectRole");
$result = $existingProjectAccess->update(['role' => $desiredProjectRole]);
$activities = $result->getActivities();
Expand Down
64 changes: 10 additions & 54 deletions src/Service/Api.php
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ public function deleteAllSessions()
*/
private function getConnectorOptions() {
$connectorOptions = [];
$connectorOptions['api_url'] = $this->config->getWithDefault('api.base_url', '');
$connectorOptions['api_url'] = $this->config->getApiUrl();
if ($this->config->has('api.accounts_api_url')) {
$connectorOptions['accounts'] = $this->config->get('api.accounts_api_url');
}
Expand Down Expand Up @@ -312,7 +312,7 @@ private function getConnectorOptions() {
return $this->onRefreshError($e);
};

$connectorOptions['auth_api_enabled'] = $this->config->get('api.auth');
$connectorOptions['auth_api_enabled'] = true;
$connectorOptions['centralized_permissions_enabled'] = $this->config->get('api.centralized_permissions');

return $connectorOptions;
Expand Down Expand Up @@ -641,20 +641,14 @@ public function getMyProjects($refresh = null)
* Return the user's project with the given ID.
*
* @param string $id The project ID.
* @param string|null $host The project's hostname. @deprecated no longer used if an api.base_url is configured.
* @param string|null $host @deprecated no longer used
* @param bool|null $refresh Whether to bypass the cache.
*
* @return Project|false
*/
public function getProject($id, $host = null, $refresh = null)
{
// Ignore the $host if an api.base_url is configured.
$apiUrl = $this->config->getWithDefault('api.base_url', '');
if ($apiUrl !== '') {
$host = null;
}

$cacheKey = sprintf('%s:project:%s:%s', $this->config->getSessionId(), $id, $host);
$cacheKey = sprintf('%s:project:%s', $this->config->getSessionId(), $id);
$cached = $this->cache->fetch($cacheKey);

if ($refresh || !$cached) {
Expand All @@ -679,10 +673,7 @@ public function getProject($id, $host = null, $refresh = null)
$project = new Project($cached, $baseUrl, $guzzleClient);
$this->debug('Loaded project from cache: ' . $id);
}
$apiUrl = $this->config->getWithDefault('api.base_url', '');
if ($apiUrl) {
$project->setApiUrl($apiUrl);
}
$project->setApiUrl($this->config->getApiUrl());

return $project;
}
Expand Down Expand Up @@ -839,34 +830,14 @@ public function getEnvironmentTypes(Project $project, $refresh = null)
* 'last_name': string,
* 'display_name': string,
* 'phone_number_verified': bool,
* 'uuid'?: string
* }
*/
public function getMyAccount($reset = false)
{
$info = ['id' => '', 'username' => '', 'email' => '', 'first_name' => '', 'last_name' => '', 'phone_number_verified' => false];
if ($this->authApiEnabled()) {
$user = $this->getUser(null, $reset);
$info = array_merge($info, $user->getProperties());
$info['display_name'] = trim($user->first_name . ' ' . $user->last_name);
} else {
$account = $this->getLegacyAccountInfo($reset);
$info = [
'id' => $account['id'],
'username' => $account['username'],
'email' => $account['mail'],
'display_name' => $account['display_name'],
];
if (isset($account['display_name'])) {
$parts = \explode(' ', $account['display_name'], 2);
if (count($parts) === 2) {
list($info['first_name'], $info['last_name']) = $parts;
} else {
$info['last_name'] = $account['display_name'];
}
}
}
return $info;
$user = $this->getUser(null, $reset);
return $user->getProperties() + [
'display_name' => trim($user->first_name . ' ' . $user->last_name),
];
}

/**
Expand Down Expand Up @@ -900,16 +871,6 @@ public function getMyUserId($reset = false)
return $this->getClient()->getMyUserId($reset);
}

/**
* Determines if the Auth API can be used, e.g. the getUser() method.
*
* @return bool
*/
public function authApiEnabled()
{
return $this->config->getWithDefault('api.auth', false) && $this->config->getWithDefault('api.base_url', '');
}

/**
* Get the logged-in user's SSH keys.
*
Expand All @@ -921,7 +882,7 @@ public function getSshKeys($reset = false)
{
$data = $this->getLegacyAccountInfo($reset);

return SshKey::wrapCollection($data['ssh_keys'], rtrim($this->config->get('api.base_url'), '/') . '/', $this->getHttpClient());
return SshKey::wrapCollection($data['ssh_keys'], rtrim($this->config->getApiUrl(), '/') . '/', $this->getHttpClient());
}

/**
Expand Down Expand Up @@ -963,8 +924,6 @@ public function getAccount(ProjectAccess $access, $reset = false)
*
* This is from the /users API which deals with basic authentication-related data.
*
* @see Api::authApiEnabled()
*
* @param string|null $id
* The user ID. Defaults to the current user.
* @param bool $reset
Expand All @@ -973,9 +932,6 @@ public function getAccount(ProjectAccess $access, $reset = false)
*/
public function getUser($id = null, $reset = false)
{
if (!$this->config->getWithDefault('api.auth', false)) {
throw new \BadMethodCallException('api.auth must be enabled for this method');
}
if ($id) {
$cacheKey = 'user:' . $id;
} else {
Expand Down
10 changes: 10 additions & 0 deletions src/Service/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -679,4 +679,14 @@ private function applyLocalDirectoryDefaults()
}
}
}

/**
* Returns the base API URL.
*
* @return string
*/
public function getApiUrl()
{
return (string) $this->get('api.base_url');
}
}
12 changes: 1 addition & 11 deletions src/Service/SshDiagnostics.php
Original file line number Diff line number Diff line change
Expand Up @@ -216,17 +216,7 @@ public function diagnoseFailure($uri, Process $failedProcess)

$this->stdErr->writeln('The SSH connection failed because access requires MFA (multi-factor authentication).');

if (!$this->api->authApiEnabled()) {
if ($this->config->has('api.mfa_setup_url')) {
$this->stdErr->writeln(\sprintf(
'Ensure that MFA is enabled on your account. Set it up at: <comment>%s</comment>',
$this->config->get('api.mfa_setup_url')
));
$this->stdErr->writeln(\sprintf('Then log in again with: <comment>%s login -f</comment>', $executable));
} else {
$this->stdErr->writeln(\sprintf('Log in again with: <comment>%s login -f</comment>', $executable));
}
} elseif ($this->api->getUser()->mfa_enabled) {
if ($this->api->getUser()->mfa_enabled) {
$this->stdErr->writeln('MFA is currently enabled on your account, but reverification is required.');
$this->stdErr->writeln(\sprintf('Log in again with: <comment>%s login -f</comment>', $executable));
} else {
Expand Down

0 comments on commit ccb7dec

Please sign in to comment.