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
54 changes: 46 additions & 8 deletions cloud_accounts.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,33 @@
$cloud_accounts = cloud_accounts();
$cloud_credentials = cloud_credentials();
$cloud_page = new \Somethingwithproof\Cloud\AccountsPage($cloud_accounts, $cloud_credentials);
$cloud_user = isset($_SESSION['sess_user_id']) && is_numeric($_SESSION['sess_user_id']) ? (int) $_SESSION['sess_user_id'] : 0;
$cloud_user = isset($_SESSION['sess_user_id']) && is_numeric($_SESSION['sess_user_id'])
? (int) $_SESSION['sess_user_id']
: 0;
$cloud_action = (string) get_nfilter_request_var('action');

switch ($cloud_action) {
case 'save':
$cloud_id = (int) get_filter_request_var('id');
$cloud_input = array();

foreach (array('provider', 'name', 'poller_id', 'credential_source', 'credential_file', 'collect_interval', 'discover_interval', 'request_share', 'monthly_ceiling', 'enabled', 'scope_account_id', 'scope_regions', 'scope_project', 'scope_tenant', 'scope_subscription') as $cloud_field) {
foreach (array(
'provider',
'name',
'poller_id',
'credential_source',
'credential_file',
'collect_interval',
'discover_interval',
'request_share',
'monthly_ceiling',
'enabled',
'scope_account_id',
'scope_regions',
'scope_project',
'scope_tenant',
'scope_subscription'
) as $cloud_field) {
$cloud_input[$cloud_field] = (string) get_nfilter_request_var($cloud_field);
}

Expand All @@ -60,7 +78,11 @@
$cloud_input['provider'] = $cloud_existing->provider->value;
}

$cloud_parsed = \Somethingwithproof\Cloud\AccountInput::parse($cloud_input, $cloud_id, \Somethingwithproof\Cloud\Provider::released());
$cloud_parsed = \Somethingwithproof\Cloud\AccountInput::parse(
$cloud_input,
$cloud_id,
\Somethingwithproof\Cloud\Provider::released()
);
$cloud_errors = $cloud_parsed->errors;

if ($cloud_parsed->account !== null && $cloud_accounts->nameTaken($cloud_parsed->account->name, $cloud_id)) {
Expand All @@ -82,7 +104,11 @@
$cloud_credentials->storeVaultCredential($cloud_saved, new \Somethingwithproof\Cloud\Secret($cloud_raw));
$cloud_accounts->recordCredentialChange($cloud_saved, $cloud_user);
} catch (\Somethingwithproof\Cloud\CredentialError $cloud_error) {
raise_message('cloud_credential', __('The account was saved, but the credential was not stored: %s', $cloud_error->getMessage(), 'cloud'), MESSAGE_LEVEL_ERROR);
raise_message(
'cloud_credential',
__('The account was saved, but the credential was not stored: %s', $cloud_error->getMessage(), 'cloud'),
MESSAGE_LEVEL_ERROR
);
}
}

Expand All @@ -98,7 +124,11 @@
exit;
case 'delete':
if ($cloud_accounts->delete((int) get_filter_request_var('id'), $cloud_user)) {
raise_message('cloud_deleted', __('The account and its collected data were deleted. Its Cacti devices and graphs were left in place.', 'cloud'), MESSAGE_LEVEL_INFO);
raise_message(
'cloud_deleted',
__('The account and its collected data were deleted. Its Cacti devices and graphs were left in place.', 'cloud'),
MESSAGE_LEVEL_INFO
);
}

header('Location: cloud_accounts.php');
Expand All @@ -107,9 +137,17 @@
$cloud_account = $cloud_accounts->find((int) get_filter_request_var('id'));

if ($cloud_account !== null) {
$cloud_status = (new \Somethingwithproof\Cloud\Verifier(\Somethingwithproof\Cloud\Drivers::production(), $cloud_credentials, $cloud_accounts))->verify($cloud_account, $cloud_user);

raise_message('cloud_verify', $cloud_status->message(), $cloud_status === \Somethingwithproof\Cloud\VerifyStatus::Ok ? MESSAGE_LEVEL_INFO : MESSAGE_LEVEL_WARN);
$cloud_status = (new \Somethingwithproof\Cloud\Verifier(
\Somethingwithproof\Cloud\Drivers::production(),
$cloud_credentials,
$cloud_accounts
))->verify($cloud_account, $cloud_user);

raise_message(
'cloud_verify',
$cloud_status->message(),
$cloud_status === \Somethingwithproof\Cloud\VerifyStatus::Ok ? MESSAGE_LEVEL_INFO : MESSAGE_LEVEL_WARN
);
}

header('Location: cloud_accounts.php');
Expand Down
6 changes: 5 additions & 1 deletion cloud_health.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,9 @@
);

top_header();
$cloud_page->render(cloud_settings(), api_user_realm_auth('cloud_accounts.php'), (int) read_config_option('poller_interval'));
$cloud_page->render(
cloud_settings(),
api_user_realm_auth('cloud_accounts.php'),
(int) read_config_option('poller_interval')
);
bottom_footer();
6 changes: 5 additions & 1 deletion lib/Account.php
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,11 @@ public function changedFields(?self $before): array {
$now = $this->toRow();
$then = $before?->toRow() ?? [];

return array_keys(array_filter($now, static fn ($value, $key) => !array_key_exists($key, $then) || $then[$key] !== $value, ARRAY_FILTER_USE_BOTH));
return array_keys(array_filter(
$now,
static fn ($value, $key) => !array_key_exists($key, $then) || $then[$key] !== $value,
ARRAY_FILTER_USE_BOTH
));
}

public function enabled(): bool {
Expand Down
32 changes: 27 additions & 5 deletions lib/AccountInput.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,11 @@
$value = strtolower(str_replace(' ', '', Row::string($input, 'scope_' . $field)));

if (!self::scopeValueValid($value, $rule)) {
$errors['scope_' . $field] = __('%s: the value does not have the form this provider uses.', self::scopeLabel($field), 'cloud');
$errors['scope_' . $field] = __(
'%s: the value does not have the form this provider uses.',
self::scopeLabel($field),
'cloud'
);
} else {
$scope[$field] = $value;
}
Expand All @@ -83,18 +87,33 @@
$file = Row::string($input, 'credential_file');

if ($source === CredentialSource::File && !CredentialFile::pathAcceptable($file)) {
$errors['credential_file'] = __('Credential File: enter an absolute path without control characters, at most 512 characters.', 'cloud');
$errors['credential_file'] = __(
'Credential File: enter an absolute path without control characters, at most 512 characters.',
'cloud'
);
}

$collect = Row::int($input, 'collect_interval', 0);
$discover = Row::int($input, 'discover_interval', 0);

if ($collect < self::MIN_COLLECT || $collect > self::MAX_INTERVAL) {
$errors['collect_interval'] = __('%s: enter whole seconds from %d to %d.', __('Collection Interval', 'cloud'), self::MIN_COLLECT, self::MAX_INTERVAL, 'cloud');
$errors['collect_interval'] = __(
'%s: enter whole seconds from %d to %d.',

Check warning on line 101 in lib/AccountInput.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Align all arguments in this list at column "7".

See more on https://sonarcloud.io/project/issues?id=somethingwithproof_plugin_cloud&issues=AaHeW09oC7n5zOm-ZUb1&open=AaHeW09oC7n5zOm-ZUb1&pullRequest=83
__('Collection Interval', 'cloud'),
self::MIN_COLLECT,
self::MAX_INTERVAL,
'cloud'
);
}

if ($discover < self::MIN_DISCOVER || $discover > self::MAX_INTERVAL) {
$errors['discover_interval'] = __('%s: enter whole seconds from %d to %d.', __('Discovery Interval', 'cloud'), self::MIN_DISCOVER, self::MAX_INTERVAL, 'cloud');
$errors['discover_interval'] = __(
'%s: enter whole seconds from %d to %d.',
__('Discovery Interval', 'cloud'),
self::MIN_DISCOVER,
self::MAX_INTERVAL,
'cloud'
);
}
$share = Row::int($input, 'request_share', 0);

Expand All @@ -108,7 +127,10 @@
$ceiling = Row::float($input, 'monthly_ceiling');

if ($ceiling === null || $ceiling < 0) {
$errors['monthly_ceiling'] = __('Monthly Ceiling: enter an amount of zero or more, or leave it blank for none.', 'cloud');
$errors['monthly_ceiling'] = __(
'Monthly Ceiling: enter an amount of zero or more, or leave it blank for none.',
'cloud'
);
}
}

Expand Down
69 changes: 59 additions & 10 deletions lib/AccountRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,12 @@
* @return list<Account>
*/
public function all(): array {
return $this->accounts(Row::rows(db_fetch_assoc_prepared('SELECT * FROM plugin_cloud_account ORDER BY name', [], true, $this->connection)));
return $this->accounts(Row::rows(db_fetch_assoc_prepared(
'SELECT * FROM plugin_cloud_account ORDER BY name',
[],
true,
$this->connection
)));
}

/**
Expand All @@ -47,11 +52,22 @@
* @return list<Account>
*/
public function enabledForPoller(int $pollerId): array {
return $this->accounts(Row::rows(db_fetch_assoc_prepared('SELECT * FROM plugin_cloud_account WHERE poller_id = ? AND admin_state = ? ORDER BY id', [$pollerId, AdminState::Enabled->value], true, $this->connection)));
return $this->accounts(Row::rows(db_fetch_assoc_prepared(
'SELECT * FROM plugin_cloud_account WHERE poller_id = ? AND admin_state = ? ORDER BY id',
[$pollerId, AdminState::Enabled->value],
true,
$this->connection
)));
}

public function nameTaken(string $name, int $exceptId): bool {
return (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_cloud_account WHERE name = ? AND id != ?', [$name, $exceptId], '', true, $this->connection) > 0;
return (int) db_fetch_cell_prepared(
'SELECT COUNT(*) FROM plugin_cloud_account WHERE name = ? AND id != ?',

Check warning on line 65 in lib/AccountRepository.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Align all arguments in this list at column "6".

See more on https://sonarcloud.io/project/issues?id=somethingwithproof_plugin_cloud&issues=AaHeW09vC7n5zOm-ZUb6&open=AaHeW09vC7n5zOm-ZUb6&pullRequest=83
[$name, $exceptId],
'',
true,
$this->connection
) > 0;
}

/**
Expand All @@ -68,12 +84,23 @@

if ($before === null) {
$columns = array_keys($row);
$ok = db_execute_prepared('INSERT INTO plugin_cloud_account (' . implode(', ', $columns) . ', created_at, updated_at) VALUES (' . implode(', ', array_fill(0, count($columns) + 2, '?')) . ')', array_merge(array_values($row), [$now, $now]), true, $this->connection);
$ok = db_execute_prepared(
'INSERT INTO plugin_cloud_account (' . implode(', ', $columns) . ', created_at, updated_at) VALUES ('
. implode(', ', array_fill(0, count($columns) + 2, '?')) . ')',
array_merge(array_values($row), [$now, $now]),
true,
$this->connection
);
$id = $ok ? (int) db_fetch_insert_id($this->connection) : 0;
$action = 'create';
} else {
$set = implode(', ', array_map(static fn (string $column): string => "$column = ?", array_keys($row)));
$ok = db_execute_prepared("UPDATE plugin_cloud_account SET $set, updated_at = ? WHERE id = ?", array_merge(array_values($row), [$now, $account->id]), true, $this->connection);
$ok = db_execute_prepared(
"UPDATE plugin_cloud_account SET $set, updated_at = ? WHERE id = ?",
array_merge(array_values($row), [$now, $account->id]),
true,
$this->connection
);
$id = $ok ? $account->id : 0;
$action = 'update';
}
Expand Down Expand Up @@ -110,7 +137,11 @@
['DELETE FROM plugin_cloud_series WHERE account_id = ?', [$id]],
['DELETE FROM plugin_cloud_lease WHERE account_id = ?', [$id]],
['DELETE FROM plugin_cloud_health WHERE account_id = ?', [$id]],
['DELETE o FROM plugin_cloud_observation o INNER JOIN plugin_cloud_resource r ON r.id = o.resource_id WHERE r.account_id = ?', [$id]],
[
'DELETE o FROM plugin_cloud_observation o INNER JOIN plugin_cloud_resource r ON r.id = o.resource_id
WHERE r.account_id = ?',
[$id]
],
['DELETE FROM plugin_cloud_resource WHERE account_id = ?', [$id]],
['DELETE FROM plugin_cloud_account WHERE id = ?', [$id]],
];
Expand Down Expand Up @@ -145,7 +176,12 @@
}

public function recordVerify(int $id, VerifyStatus $status, int $userId): void {
db_execute_prepared('UPDATE plugin_cloud_account SET verify_status = ?, verified_at = ? WHERE id = ?', [$status->value, $this->clock->now(), $id], true, $this->connection);
db_execute_prepared(
'UPDATE plugin_cloud_account SET verify_status = ?, verified_at = ? WHERE id = ?',
[$status->value, $this->clock->now(), $id],
true,
$this->connection
);

$this->audit($id, $userId, 'verify', ['verify_status']);
}
Expand All @@ -163,7 +199,12 @@
public function auditLog(int $accountId, int $limit = 50): array {
$entries = [];

foreach (Row::rows(db_fetch_assoc_prepared('SELECT * FROM plugin_cloud_audit WHERE account_id = ? ORDER BY id DESC LIMIT ' . max(1, $limit), [$accountId], true, $this->connection)) as $row) {
foreach (Row::rows(db_fetch_assoc_prepared(
'SELECT * FROM plugin_cloud_audit WHERE account_id = ? ORDER BY id DESC LIMIT ' . max(1, $limit),
[$accountId],
true,
$this->connection
)) as $row) {
$fields = Row::string($row, 'fields');

$entries[] = [
Expand All @@ -186,7 +227,12 @@
* @param list<string> $fields
*/
private function audit(int $accountId, int $userId, string $action, array $fields): void {
db_execute_prepared('INSERT INTO plugin_cloud_audit (account_id, user_id, changed_at, action, fields) VALUES (?, ?, ?, ?, ?)', [$accountId, $userId, $this->clock->now(), $action, implode(',', $fields)], true, $this->connection);
db_execute_prepared(
'INSERT INTO plugin_cloud_audit (account_id, user_id, changed_at, action, fields) VALUES (?, ?, ?, ?, ?)',
[$accountId, $userId, $this->clock->now(), $action, implode(',', $fields)],
true,
$this->connection
);
}

/**
Expand All @@ -200,7 +246,10 @@
$account = Account::fromRow($row);

if ($account === null) {
Log::warning(sprintf('Account row %d has an unknown provider or credential source and was skipped', Row::int($row, 'id')));
Log::warning(sprintf(
'Account row %d has an unknown provider or credential source and was skipped',

Check warning on line 250 in lib/AccountRepository.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Align all arguments in this list at column "8".

See more on https://sonarcloud.io/project/issues?id=somethingwithproof_plugin_cloud&issues=AaHeW09vC7n5zOm-ZUcA&open=AaHeW09vC7n5zOm-ZUcA&pullRequest=83
Row::int($row, 'id')
));

continue;
}
Expand Down
Loading
Loading