From ae04d1afc683a487939c2d478af0ee5e7263e754 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 00:23:29 -0800 Subject: [PATCH 1/2] chore: fix the SonarQube Cloud findings that fit the code style - build_gettext.sh names generate()'s output path instead of reusing $1 (shell:S7679). - Test fixtures that ran two statements in a one-line closure now put each on its own line (php:S122). Refs #38 Signed-off-by: Thomas Vincent --- locales/build_gettext.sh | 6 ++++-- tests/Unit/HealthWarningsTest.php | 24 ++++++++++++++++++++---- tests/Unit/VaultTest.php | 12 ++++++++++-- 3 files changed, 34 insertions(+), 8 deletions(-) diff --git a/locales/build_gettext.sh b/locales/build_gettext.sh index ebcb7c7..d102b38 100755 --- a/locales/build_gettext.sh +++ b/locales/build_gettext.sh @@ -37,16 +37,18 @@ command -v xgettext >/dev/null 2>&1 || { echo "ERROR: Unable to locate xgettext VERSION=$(sed -n 's/^version *= *//p' INFO) generate() { + out=$1 + # shellcheck disable=SC2046 xgettext --no-wrap --add-location=file --from-code=UTF-8 --copyright-holder="Thomas Vincent" \ --package-name="cloud" --package-version="$VERSION" --msgid-bugs-address="https://github.com/somethingwithproof/plugin_cloud/issues" \ -F -L PHP -k__gettext -k__ -k__n:1,2 -k__x:1c,2 -k__xn:1c,2,3 -k__esc -k__esc_n:1,2 -k__esc_x:1c,2 -k__esc_xn:1c,2,3 -k__date \ - -o "$1" $(find . -maxdepth 2 -name '*.php' -not -path './tests/*' | sort) + -o "$out" $(find . -maxdepth 2 -name '*.php' -not -path './tests/*' | sort) sed -e 's/FULL NAME /Thomas Vincent /' \ -e 's/LANGUAGE /Thomas Vincent /' \ -e 's/CHARSET/UTF-8/' \ - -e '/^"POT-Creation-Date:/d' "$1" > "$1.tmp" && mv "$1.tmp" "$1" + -e '/^"POT-Creation-Date:/d' "$out" > "$out.tmp" && mv "$out.tmp" "$out" } if [ "${1:-}" = "--check" ]; then diff --git a/tests/Unit/HealthWarningsTest.php b/tests/Unit/HealthWarningsTest.php index f8a22de..cba8540 100644 --- a/tests/Unit/HealthWarningsTest.php +++ b/tests/Unit/HealthWarningsTest.php @@ -60,8 +60,16 @@ function cloud_warnings(string $key, array $accounts, int $poller = 300): array it('warns everyone when the vault key file is missing or refused', function (string $fixture, string $reason) { $path = match ($fixture) { 'missing' => $this->dir . '/none.key', - 'shared' => (function () { chmod($this->key, 0644); return $this->key; })->call($this), - 'short' => (function () { file_put_contents($this->key, 'abc'); return $this->key; })->call($this), + 'shared' => (function () { + chmod($this->key, 0644); + + return $this->key; + })->call($this), + 'short' => (function () { + file_put_contents($this->key, 'abc'); + + return $this->key; + })->call($this), }; $warnings = cloud_warnings($path, [cloud_warn_account()]); @@ -79,8 +87,16 @@ function cloud_warnings(string $key, array $accounts, int $poller = 300): array it('warns Cloud Admin only when a credential file is unsafe', function (string $fixture, string $reason) { $path = match ($fixture) { 'missing' => $this->dir . '/none', - 'shared' => (function () { chmod($this->token, 0604); return $this->token; })->call($this), - 'link' => (function () { symlink($this->token, $this->dir . '/link'); return $this->dir . '/link'; })->call($this), + 'shared' => (function () { + chmod($this->token, 0604); + + return $this->token; + })->call($this), + 'link' => (function () { + symlink($this->token, $this->dir . '/link'); + + return $this->dir . '/link'; + })->call($this), }; $warnings = cloud_warnings($this->key, [cloud_warn_account(['credential_source' => 'file', 'credential_file' => $path])]); diff --git a/tests/Unit/VaultTest.php b/tests/Unit/VaultTest.php index 903ef80..367bbda 100644 --- a/tests/Unit/VaultTest.php +++ b/tests/Unit/VaultTest.php @@ -112,8 +112,16 @@ function cloud_refusal(callable $read): string { $path = match ($case) { 'relative' => 'etc/cloud.key', 'missing' => $dir . '/missing.key', - 'symlink' => (function () use ($dir) { symlink(cloud_file($dir, 'target', bin2hex(random_bytes(32))), $dir . '/link'); return $dir . '/link'; })(), - 'directory' => (function () use ($dir) { mkdir($dir . '/sub', 0700); return $dir . '/sub'; })(), + 'symlink' => (function () use ($dir) { + symlink(cloud_file($dir, 'target', bin2hex(random_bytes(32))), $dir . '/link'); + + return $dir . '/link'; + })(), + 'directory' => (function () use ($dir) { + mkdir($dir . '/sub', 0700); + + return $dir . '/sub'; + })(), 'world-read' => cloud_file($dir, 'wr', bin2hex(random_bytes(32)), 0604), 'world-write'=> cloud_file($dir, 'ww', bin2hex(random_bytes(32)), 0602), 'short' => cloud_file($dir, 'short', random_bytes(31)), From 58905f86d82ebff7ca618e8fe1a49100803cc3cd Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 00:37:39 -0800 Subject: [PATCH 2/2] style: wrap lines longer than 120 characters SonarQube Cloud's php:S103 flagged 344 lines over 120 characters. They are wrapped in the existing style: tabs, braces on the same line, one argument or array element per line, SQL broken at whitespace, and long literals joined with the same resulting text. A token comparison against main, folding joined literals, matches for every file but two interpolated strings, which keep their text. Seven lines stay long: each is a translated string alone on its line, and splitting it would change its translation key. The placeholder rule in SourceRulesTest now allows a line break after __(, which the wrapping introduced; without it the rule silently skipped those strings. The translation template is regenerated: the same strings, in the order the wrapped sources now give. Refs #38 Signed-off-by: Thomas Vincent --- cloud_accounts.php | 54 ++++- cloud_health.php | 6 +- lib/Account.php | 6 +- lib/AccountInput.php | 32 ++- lib/AccountRepository.php | 69 +++++- lib/AccountsPage.php | 112 ++++++++-- lib/CloudResource.php | 5 +- lib/Collector.php | 39 +++- lib/CredentialStore.php | 6 +- lib/GuardedTransport.php | 5 +- lib/HealthPage.php | 39 +++- lib/HealthRepository.php | 27 ++- lib/HealthWarnings.php | 32 ++- lib/LeaseRepository.php | 38 +++- lib/Observation.php | 8 +- lib/ObservationRepository.php | 28 ++- lib/Operation.php | 5 +- lib/Redactor.php | 9 +- lib/ResourceRepository.php | 35 +++- lib/Schema.php | 98 +++++++-- lib/SecretRepository.php | 39 +++- lib/SecureFile.php | 7 +- lib/SeriesRepository.php | 7 +- lib/Settings.php | 20 +- lib/SettingsRepository.php | 7 +- lib/SocketTransport.php | 9 +- lib/TransportError.php | 8 +- lib/Vault.php | 21 +- lib/VaultEntry.php | 8 +- lib/VerifyStatus.php | 5 +- locales/po/cacti.pot | 30 +-- poller_cloud.php | 33 ++- setup.php | 31 ++- tests/Integration/LifecycleTest.php | 9 +- tests/Security/SourceRulesTest.php | 28 ++- tests/Transport/SocketTransportTest.php | 151 +++++++++++--- tests/Unit/AccountTest.php | 91 ++++++-- tests/Unit/DriverContractTest.php | 64 +++++- tests/Unit/FreshnessTest.php | 39 +++- tests/Unit/HealthWarningsTest.php | 62 +++++- tests/Unit/VaultTest.php | 47 ++++- tests/bin/collector-flow.php | 92 ++++++-- tests/bin/collector-restart.php | 83 ++++++-- tests/bin/lifecycle.php | 90 ++++++-- tests/bin/page-check.php | 27 ++- tests/bin/page-permissions.php | 125 +++++++++-- tests/bin/php-guard-check.php | 30 ++- tests/bootstrap-unit.php | 9 +- tests/signing-vectors/AwsSigV4.php | 6 +- tests/signing-vectors/jwt-rs256.php | 28 ++- tests/signing-vectors/run.php | 13 +- tests/transport-spike/CurlTransport.php | 23 +- tests/transport-spike/SocketTransport.php | 18 +- tests/transport-spike/StreamTransport.php | 9 +- tests/transport-spike/make-certs.php | 9 +- tests/transport-spike/server.php | 44 +++- tests/transport-spike/spike.php | 242 ++++++++++++++++++---- 57 files changed, 1846 insertions(+), 371 deletions(-) diff --git a/cloud_accounts.php b/cloud_accounts.php index 1664efb..a68d464 100644 --- a/cloud_accounts.php +++ b/cloud_accounts.php @@ -36,7 +36,9 @@ $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) { @@ -44,7 +46,23 @@ $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); } @@ -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)) { @@ -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 + ); } } @@ -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'); @@ -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'); diff --git a/cloud_health.php b/cloud_health.php index 65c24fb..c333f70 100644 --- a/cloud_health.php +++ b/cloud_health.php @@ -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(); diff --git a/lib/Account.php b/lib/Account.php index 038eb06..9c0b795 100644 --- a/lib/Account.php +++ b/lib/Account.php @@ -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 { diff --git a/lib/AccountInput.php b/lib/AccountInput.php index cbc4b68..4dc784a 100644 --- a/lib/AccountInput.php +++ b/lib/AccountInput.php @@ -68,7 +68,11 @@ public static function parse(array $input, int $id, array $offered): self { $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; } @@ -83,18 +87,33 @@ public static function parse(array $input, int $id, array $offered): self { $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.', + __('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); @@ -108,7 +127,10 @@ public static function parse(array $input, int $id, array $offered): self { $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' + ); } } diff --git a/lib/AccountRepository.php b/lib/AccountRepository.php index 93221a9..548f679 100644 --- a/lib/AccountRepository.php +++ b/lib/AccountRepository.php @@ -38,7 +38,12 @@ public function find(int $id): ?Account { * @return list */ 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 + ))); } /** @@ -47,11 +52,22 @@ public function all(): array { * @return list */ 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 != ?', + [$name, $exceptId], + '', + true, + $this->connection + ) > 0; } /** @@ -68,12 +84,23 @@ public function save(Account $account, int $userId): int { 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'; } @@ -110,7 +137,11 @@ public function delete(int $id, int $userId): bool { ['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]], ]; @@ -145,7 +176,12 @@ public function delete(int $id, int $userId): bool { } 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']); } @@ -163,7 +199,12 @@ public function recordCredentialChange(int $id, int $userId): void { 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[] = [ @@ -186,7 +227,12 @@ private function inTransaction(): bool { * @param list $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 + ); } /** @@ -200,7 +246,10 @@ private function accounts(array $rows): array { $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', + Row::int($row, 'id') + )); continue; } diff --git a/lib/AccountsPage.php b/lib/AccountsPage.php index 37975b6..5d2aede 100644 --- a/lib/AccountsPage.php +++ b/lib/AccountsPage.php @@ -38,7 +38,12 @@ public function renderList(): void { html_start_box(__('Cloud Accounts', 'cloud'), '100%', '', '3', 'center', self::FILE . '?action=edit'); print '' . implode('', array_map('html_escape', [ - __('Name', 'cloud'), __('Provider', 'cloud'), __('Credential', 'cloud'), __('State', 'cloud'), __('Verify', 'cloud'), __('Actions', 'cloud'), + __('Name', 'cloud'), + __('Provider', 'cloud'), + __('Credential', 'cloud'), + __('State', 'cloud'), + __('Verify', 'cloud'), + __('Actions', 'cloud'), ])) . ''; $accounts = $this->accounts->all(); @@ -49,12 +54,15 @@ public function renderList(): void { foreach ($accounts as $account) { print '' - . '' . html_escape($account->name) . '' + . '' + . html_escape($account->name) . '' . '' . html_escape($account->provider->label()) . '' . '' . html_escape($this->credentialSummary($account)) . '' . '' . html_escape($account->enabled() ? __('Enabled', 'cloud') : __('Disabled', 'cloud')) . '' - . '' . html_escape($account->verifyStatus->message()) . '' - . '' . $this->actionForm($account->id, 'verify', __('Verify', 'cloud')) . ' ' . $this->actionForm($account->id, 'delete', __('Delete', 'cloud')) . '' + . '' + . html_escape($account->verifyStatus->message()) . '' + . '' . $this->actionForm($account->id, 'verify', __('Verify', 'cloud')) . ' ' + . $this->actionForm($account->id, 'delete', __('Delete', 'cloud')) . '' . ''; } @@ -70,39 +78,98 @@ public function renderEdit(?Account $account, array $input = [], array $errors = return array_key_exists($field, $input) ? Row::string($input, $field) : $current; }; - $provider = Provider::tryFrom($value('provider', $account?->provider->value ?? Provider::DigitalOcean->value)) ?? Provider::DigitalOcean; + $provider = Provider::tryFrom($value('provider', $account?->provider->value ?? Provider::DigitalOcean->value)) + ?? Provider::DigitalOcean; $offered = $account === null ? Provider::released() : [$account->provider]; print '
'; - html_start_box($account === null ? __('New Cloud Account', 'cloud') : __('Cloud Account: %s', html_escape($account->name), 'cloud'), '100%', '', '3', 'center', ''); + html_start_box( + $account === null ? __('New Cloud Account', 'cloud') : __('Cloud Account: %s', html_escape($account->name), 'cloud'), + '100%', + '', + '3', + 'center', + '' + ); foreach ($errors as $message) { print '' . html_escape($message) . ''; } - $this->select('provider', __('Provider', 'cloud'), array_combine(array_map(static fn (Provider $p): string => $p->value, $offered), array_map(static fn (Provider $p): string => $p->label(), $offered)), $provider->value); + $this->select( + 'provider', + __('Provider', 'cloud'), + array_combine( + array_map(static fn (Provider $p): string => $p->value, $offered), + array_map(static fn (Provider $p): string => $p->label(), $offered) + ), + $provider->value + ); $this->text('name', __('Name', 'cloud'), $value('name', $account->name ?? ''), 100); foreach ($provider->scopeFields() as $field => $rule) { - $this->text('scope_' . $field, AccountInput::scopeLabel($field), $value('scope_' . $field, $account?->scope[$field] ?? ''), 512); + $this->text( + 'scope_' . $field, + AccountInput::scopeLabel($field), + $value('scope_' . $field, $account?->scope[$field] ?? ''), + 512 + ); } $sources = $provider->credentialSources(); - $this->select('credential_source', __('Credential Source', 'cloud'), array_combine(array_map(static fn (CredentialSource $s): string => $s->value, $sources), array_map(static fn (CredentialSource $s): string => $s->label(), $sources)), $value('credential_source', $account?->credentialSource->value ?? CredentialSource::Vault->value)); - $this->text('credential_file', __('Credential File', 'cloud'), $value('credential_file', $account->credentialFile ?? ''), 512); + $this->select( + 'credential_source', + __('Credential Source', 'cloud'), + array_combine( + array_map(static fn (CredentialSource $s): string => $s->value, $sources), + array_map(static fn (CredentialSource $s): string => $s->label(), $sources) + ), + $value('credential_source', $account?->credentialSource->value ?? CredentialSource::Vault->value) + ); + $this->text( + 'credential_file', + __('Credential File', 'cloud'), + $value('credential_file', $account->credentialFile ?? ''), + 512 + ); // The credential is write-only: the box is always empty, and leaving it // empty keeps the stored value. - print '' . html_escape(__('Credential', 'cloud')) . '
' . html_escape($account !== null && $this->credentials->hasVaultCredential($account->id) ? __('A credential is stored. Leave blank to keep it.', 'cloud') : __('Paste the token or key to store in the vault.', 'cloud')) . '' + print '' . html_escape(__('Credential', 'cloud')) . '
' . html_escape( + $account !== null && $this->credentials->hasVaultCredential($account->id) + ? __('A credential is stored. Leave blank to keep it.', 'cloud') + : __('Paste the token or key to store in the vault.', 'cloud') + ) . '' . ''; - $this->text('collect_interval', __('Collection Interval', 'cloud'), $value('collect_interval', (string) ($account->collectInterval ?? AccountInput::DEFAULT_COLLECT)), 5); - $this->text('discover_interval', __('Discovery Interval', 'cloud'), $value('discover_interval', (string) ($account->discoverInterval ?? AccountInput::DEFAULT_DISCOVER)), 5); - $this->text('request_share', __('Request Share', 'cloud'), $value('request_share', (string) ($account->requestShare ?? AccountInput::DEFAULT_SHARE)), 3); - $this->text('monthly_ceiling', __('Monthly Ceiling', 'cloud'), $value('monthly_ceiling', $account?->monthlyCeiling === null ? '' : (string) $account->monthlyCeiling), 12); + $this->text( + 'collect_interval', + __('Collection Interval', 'cloud'), + $value('collect_interval', (string) ($account->collectInterval ?? AccountInput::DEFAULT_COLLECT)), + 5 + ); + $this->text( + 'discover_interval', + __('Discovery Interval', 'cloud'), + $value('discover_interval', (string) ($account->discoverInterval ?? AccountInput::DEFAULT_DISCOVER)), + 5 + ); + $this->text( + 'request_share', + __('Request Share', 'cloud'), + $value('request_share', (string) ($account->requestShare ?? AccountInput::DEFAULT_SHARE)), + 3 + ); + $this->text( + 'monthly_ceiling', + __('Monthly Ceiling', 'cloud'), + $value('monthly_ceiling', $account?->monthlyCeiling === null ? '' : (string) $account->monthlyCeiling), + 12 + ); $enabled = array_key_exists('enabled', $input) ? Row::bool($input, 'enabled') : ($account?->enabled() ?? true); - print '' . html_escape(__('Enabled', 'cloud')) . ''; + print '' . html_escape(__('Enabled', 'cloud')) . ''; html_end_box(); @@ -115,7 +182,9 @@ public function renderEdit(?Account $account, array $input = [], array $errors = private function credentialSummary(Account $account): string { return match ($account->credentialSource) { - CredentialSource::Vault => $this->credentials->hasVaultCredential($account->id) ? __('Stored in the vault', 'cloud') : __('None stored', 'cloud'), + CredentialSource::Vault => $this->credentials->hasVaultCredential($account->id) + ? __('Stored in the vault', 'cloud') + : __('None stored', 'cloud'), CredentialSource::File => __('File on the poller', 'cloud'), CredentialSource::Instance => __('Instance identity', 'cloud'), }; @@ -131,17 +200,20 @@ private function actionForm(int $id, string $action, string $label): string { private function text(string $name, string $label, string $value, int $length): void { print '' - . ''; + . ''; } /** * @param array $options */ private function select(string $name, string $label, array $options, string $current): void { - print ''; foreach ($options as $value => $text) { - print ''; + print ''; } print ''; diff --git a/lib/CloudResource.php b/lib/CloudResource.php index 3c458ab..23d700e 100644 --- a/lib/CloudResource.php +++ b/lib/CloudResource.php @@ -44,7 +44,10 @@ public function __construct(string $type, string $providerId, string $name, stri */ private static function identity(string $value, int $length, string $what): string { if ($value === '' || mb_strlen($value) > $length || preg_match('/[\x00-\x1f\x7f]/', $value) === 1) { - throw new DriverError(ErrorClass::Malformed, 'resource ' . $what . ' is empty, longer than ' . $length . ' characters, or holds control characters'); + throw new DriverError( + ErrorClass::Malformed, + 'resource ' . $what . ' is empty, longer than ' . $length . ' characters, or holds control characters' + ); } return $value; diff --git a/lib/Collector.php b/lib/Collector.php index d0ea23f..36cbe19 100644 --- a/lib/Collector.php +++ b/lib/Collector.php @@ -74,7 +74,10 @@ public function run(int $pollerId, int $budgetSeconds): array { $lastRun[$account->id] = $this->leases->lastAcquired($account->id); } - usort($accounts, static fn (Account $a, Account $b): int => [$lastRun[$a->id], $a->id] <=> [$lastRun[$b->id], $b->id]); + usort( + $accounts, + static fn (Account $a, Account $b): int => [$lastRun[$a->id], $a->id] <=> [$lastRun[$b->id], $b->id] + ); foreach ($accounts as $account) { if ($this->clock->now() - $started >= $budgetSeconds) { @@ -116,7 +119,20 @@ private function runAccount(Account $account): void { $driver = $this->drivers->for($account); if ($driver === null) { - $this->health->save(new AccountHealth($account->id, $now, $this->clock->now(), microtime(true) - $start, CollectionState::Failed, ErrorClass::Config, discoveredAt: $previous->discoveredAt, discovery: $previous->discovery), $this->holder, $this->clock->now()); + $this->health->save( + new AccountHealth( + $account->id, + $now, + $this->clock->now(), + microtime(true) - $start, + CollectionState::Failed, + ErrorClass::Config, + discoveredAt: $previous->discoveredAt, + discovery: $previous->discovery + ), + $this->holder, + $this->clock->now() + ); return; } @@ -125,7 +141,20 @@ private function runAccount(Account $account): void { $credential = $this->credentials->credentialFor($account); } catch (CredentialError $e) { Log::warning(sprintf('Account %d: credential unavailable: %s', $account->id, $e->getMessage())); - $this->health->save(new AccountHealth($account->id, $now, $this->clock->now(), microtime(true) - $start, CollectionState::Failed, ErrorClass::Config, discoveredAt: $previous->discoveredAt, discovery: $previous->discovery), $this->holder, $this->clock->now()); + $this->health->save( + new AccountHealth( + $account->id, + $now, + $this->clock->now(), + microtime(true) - $start, + CollectionState::Failed, + ErrorClass::Config, + discoveredAt: $previous->discoveredAt, + discovery: $previous->discovery + ), + $this->holder, + $this->clock->now() + ); return; } @@ -140,7 +169,9 @@ private function runAccount(Account $account): void { try { $inventory = $driver->discover($account, $credential); $requests += $inventory->requests; - $discovery = $this->resources->sync($account->id, $inventory, $this->leases, $this->holder) ? CollectionState::Ok : CollectionState::Partial; + $discovery = $this->resources->sync($account->id, $inventory, $this->leases, $this->holder) + ? CollectionState::Ok + : CollectionState::Partial; $discoveredAt = $now; } catch (DriverError|TransportError $e) { $discovery = CollectionState::Failed; diff --git a/lib/CredentialStore.php b/lib/CredentialStore.php index 6a9d541..f10dca4 100644 --- a/lib/CredentialStore.php +++ b/lib/CredentialStore.php @@ -56,7 +56,11 @@ public function storeVaultCredential(int $accountId, Secret $secret): void { throw CredentialError::because('the credential is empty or too long'); } - if (!$this->secrets->store($accountId, SecretRepository::CREDENTIAL, $this->vault()->encrypt($secret, $accountId, SecretRepository::CREDENTIAL))) { + if (!$this->secrets->store( + $accountId, + SecretRepository::CREDENTIAL, + $this->vault()->encrypt($secret, $accountId, SecretRepository::CREDENTIAL) + )) { throw CredentialError::because('the credential could not be stored'); } } diff --git a/lib/GuardedTransport.php b/lib/GuardedTransport.php index 2717291..37346a7 100644 --- a/lib/GuardedTransport.php +++ b/lib/GuardedTransport.php @@ -42,7 +42,10 @@ public function allows(HttpRequest $request): ?Operation { public function send(HttpRequest $request): HttpResponse { if ($this->allows($request) === null) { - throw new TransportError('operation_refused', $request->method . ' ' . (string) parse_url($request->url, PHP_URL_PATH)); + throw new TransportError( + 'operation_refused', + $request->method . ' ' . (string) parse_url($request->url, PHP_URL_PATH) + ); } return $this->inner->send($request); diff --git a/lib/HealthPage.php b/lib/HealthPage.php index 56be937..b437571 100644 --- a/lib/HealthPage.php +++ b/lib/HealthPage.php @@ -70,7 +70,16 @@ public function render(Settings $settings, bool $admin, int $pollerInterval): vo html_start_box(__('Cloud Collection', 'cloud'), '100%', '', '3', 'center', ''); - $headers = [__('Account', 'cloud'), __('Collection', 'cloud'), __('Last Run', 'cloud'), __('Series Read', 'cloud'), __('Requests', 'cloud'), __('Discovery', 'cloud'), __('Resources', 'cloud'), __('Data', 'cloud')]; + $headers = [ + __('Account', 'cloud'), + __('Collection', 'cloud'), + __('Last Run', 'cloud'), + __('Series Read', 'cloud'), + __('Requests', 'cloud'), + __('Discovery', 'cloud'), + __('Resources', 'cloud'), + __('Data', 'cloud') + ]; if ($admin) { array_splice($headers, 1, 0, [__('Credential', 'cloud')]); @@ -79,7 +88,8 @@ public function render(Settings $settings, bool $admin, int $pollerInterval): vo print '' . implode('', array_map('html_escape', $headers)) . ''; if ($accounts === []) { - print '' . html_escape(__('No cloud accounts yet.', 'cloud')) . ''; + print '' + . html_escape(__('No cloud accounts yet.', 'cloud')) . ''; } foreach ($accounts as $account) { @@ -111,7 +121,12 @@ public function row(Account $account): array { $state = match (true) { // A recent datapoint without a value is still no measurement. $entry['observation']->value === null => 'unknown', - $entry['status'] === 'ok' => $this->freshness->evaluate($entry['observation'], $account->collectInterval, 0, $account->collectInterval)->value, + $entry['status'] === 'ok' => $this->freshness->evaluate( + $entry['observation'], + $account->collectInterval, + 0, + $account->collectInterval + )->value, default => $entry['status'], }; @@ -126,14 +141,24 @@ public function row(Account $account): array { $health->runStarted > 0 ? $this->age($health->runStarted) : __('Never', 'cloud'), $health->seriesTotal > 0 ? $health->seriesRead . ' / ' . $health->seriesTotal : '-', (string) $health->requests, - $health->discoveredAt > 0 ? $health->discovery->value . ', ' . $this->age($health->discoveredAt) : __('Never', 'cloud'), - $counts === [] ? '-' : implode(', ', array_map(static fn (string $state, int $n): string => "$state $n", array_keys($counts), $counts)), - $freshness === [] ? '-' : implode(', ', array_map(static fn (string $state, int $n): string => "$state $n", array_keys($freshness), $freshness)), + $health->discoveredAt > 0 + ? $health->discovery->value . ', ' . $this->age($health->discoveredAt) + : __('Never', 'cloud'), + $counts === [] ? '-' : implode( + ', ', + array_map(static fn (string $state, int $n): string => "$state $n", array_keys($counts), $counts) + ), + $freshness === [] ? '-' : implode( + ', ', + array_map(static fn (string $state, int $n): string => "$state $n", array_keys($freshness), $freshness) + ), ]; } private function collectionLabel(AccountHealth $health): string { - return $health->error === null ? $health->collection->value : $health->collection->value . ' (' . $health->error->value . ')'; + return $health->error === null + ? $health->collection->value + : $health->collection->value . ' (' . $health->error->value . ')'; } private function age(int $time): string { diff --git a/lib/HealthRepository.php b/lib/HealthRepository.php index a5341d9..b91ed27 100644 --- a/lib/HealthRepository.php +++ b/lib/HealthRepository.php @@ -24,7 +24,12 @@ public function __construct(private readonly \PDO|false $connection) { } public function find(int $accountId): AccountHealth { - $row = db_fetch_row_prepared('SELECT * FROM plugin_cloud_health WHERE account_id = ?', [$accountId], true, $this->connection); + $row = db_fetch_row_prepared( + 'SELECT * FROM plugin_cloud_health WHERE account_id = ?', + [$accountId], + true, + $this->connection + ); return (is_array($row) ? AccountHealth::fromRow($row) : null) ?? new AccountHealth($accountId); } @@ -35,13 +40,21 @@ public function find(int $accountId): AccountHealth { * holder's health in place. */ public function save(AccountHealth $health, string $holder, int $now): void { - db_execute_prepared('INSERT INTO plugin_cloud_health (account_id, run_started, run_finished, run_duration, collection, error_class, requests, series_total, series_read, discovered_at, discovery, credential) - SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? FROM plugin_cloud_lease l WHERE l.account_id = ? AND l.holder = ? AND l.expires_at >= ? - ON DUPLICATE KEY UPDATE run_started = VALUES(run_started), run_finished = VALUES(run_finished), run_duration = VALUES(run_duration), collection = VALUES(collection), - error_class = VALUES(error_class), requests = VALUES(requests), series_total = VALUES(series_total), series_read = VALUES(series_read), + db_execute_prepared('INSERT INTO plugin_cloud_health (account_id, run_started, run_finished, run_duration, collection, + error_class, requests, series_total, series_read, discovered_at, discovery, credential) + SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? FROM plugin_cloud_lease l + WHERE l.account_id = ? AND l.holder = ? AND l.expires_at >= ? + ON DUPLICATE KEY UPDATE run_started = VALUES(run_started), run_finished = VALUES(run_finished), + run_duration = VALUES(run_duration), collection = VALUES(collection), + error_class = VALUES(error_class), requests = VALUES(requests), series_total = VALUES(series_total), + series_read = VALUES(series_read), discovered_at = VALUES(discovered_at), discovery = VALUES(discovery), credential = VALUES(credential)', [ - $health->accountId, $health->runStarted, $health->runFinished, $health->runDuration, $health->collection->value, $health->error->value ?? '', - $health->requests, $health->seriesTotal, $health->seriesRead, $health->discoveredAt, $health->discovery->value, $health->error === ErrorClass::Auth ? 'invalid' : ($health->error === ErrorClass::Permission ? 'permission' : 'unknown'), + $health->accountId, $health->runStarted, $health->runFinished, $health->runDuration, + $health->collection->value, $health->error->value ?? '', + $health->requests, $health->seriesTotal, $health->seriesRead, $health->discoveredAt, $health->discovery->value, + $health->error === ErrorClass::Auth + ? 'invalid' + : ($health->error === ErrorClass::Permission ? 'permission' : 'unknown'), $health->accountId, $holder, $now, ], true, $this->connection); } diff --git a/lib/HealthWarnings.php b/lib/HealthWarnings.php index ece4fb6..1da27ff 100644 --- a/lib/HealthWarnings.php +++ b/lib/HealthWarnings.php @@ -61,7 +61,14 @@ public function for(Settings $settings, array $accounts, int $pollerInterval): a try { ($this->keyCheck)($settings->vaultKeyFile); } catch (CredentialError $e) { - $warnings[] = ['message' => __('The vault key file cannot be used: %s. Accounts that store credentials in the vault cannot be verified or collected here.', $e->getMessage(), 'cloud'), 'admin' => false]; + $warnings[] = [ + 'message' => __( + 'The vault key file cannot be used: %s. Accounts that store credentials in the vault cannot be verified or collected here.', + $e->getMessage(), + 'cloud' + ), + 'admin' => false + ]; } foreach ($accounts as $account) { @@ -73,7 +80,10 @@ public function for(Settings $settings, array $accounts, int $pollerInterval): a try { ($this->fileCheck)($account->credentialFile); } catch (CredentialError $e) { - $warnings[] = ['message' => __('%s: the credential file cannot be used: %s.', $account->name, $e->getMessage(), 'cloud'), 'admin' => true]; + $warnings[] = [ + 'message' => __('%s: the credential file cannot be used: %s.', $account->name, $e->getMessage(), 'cloud'), + 'admin' => true + ]; } } @@ -104,7 +114,21 @@ private function intervalWarning(Account $account, int $pollerInterval): ?string } return $account->collectInterval < $pollerInterval - ? __('%s: the collection interval of %d seconds is shorter than the poller interval of %d seconds, so it is collected every %d seconds.', $account->name, $account->collectInterval, $pollerInterval, $effective, 'cloud') - : __('%s: the collection interval of %d seconds is not a multiple of the poller interval of %d seconds, so it is collected every %d seconds.', $account->name, $account->collectInterval, $pollerInterval, $effective, 'cloud'); + ? __( + '%s: the collection interval of %d seconds is shorter than the poller interval of %d seconds, so it is collected every %d seconds.', + $account->name, + $account->collectInterval, + $pollerInterval, + $effective, + 'cloud' + ) + : __( + '%s: the collection interval of %d seconds is not a multiple of the poller interval of %d seconds, so it is collected every %d seconds.', + $account->name, + $account->collectInterval, + $pollerInterval, + $effective, + 'cloud' + ); } } diff --git a/lib/LeaseRepository.php b/lib/LeaseRepository.php index caa191d..27a9b54 100644 --- a/lib/LeaseRepository.php +++ b/lib/LeaseRepository.php @@ -31,14 +31,31 @@ public function __construct(private readonly \PDO|false $connection, private rea public function acquire(int $accountId, string $holder, int $seconds): bool { $now = $this->clock->now(); - db_execute_prepared('INSERT IGNORE INTO plugin_cloud_lease (account_id, holder, acquired_at, expires_at) VALUES (?, ?, 0, 0)', [$accountId, ''], true, $this->connection); - db_execute_prepared('UPDATE plugin_cloud_lease SET holder = ?, acquired_at = ?, expires_at = ? WHERE account_id = ? AND (holder = ? OR expires_at < ?)', [$holder, $now, $now + $seconds, $accountId, $holder, $now], true, $this->connection); + db_execute_prepared( + 'INSERT IGNORE INTO plugin_cloud_lease (account_id, holder, acquired_at, expires_at) VALUES (?, ?, 0, 0)', + [$accountId, ''], + true, + $this->connection + ); + db_execute_prepared( + 'UPDATE plugin_cloud_lease SET holder = ?, acquired_at = ?, expires_at = ? + WHERE account_id = ? AND (holder = ? OR expires_at < ?)', + [$holder, $now, $now + $seconds, $accountId, $holder, $now], + true, + $this->connection + ); return $this->holds($accountId, $holder); } public function holds(int $accountId, string $holder): bool { - return (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_cloud_lease WHERE account_id = ? AND holder = ? AND expires_at >= ?', [$accountId, $holder, $this->clock->now()], '', true, $this->connection) === 1; + return (int) db_fetch_cell_prepared( + 'SELECT COUNT(*) FROM plugin_cloud_lease WHERE account_id = ? AND holder = ? AND expires_at >= ?', + [$accountId, $holder, $this->clock->now()], + '', + true, + $this->connection + ) === 1; } /** @@ -47,10 +64,21 @@ public function holds(int $accountId, string $holder): bool { * were never written. */ public function lastAcquired(int $accountId): int { - return (int) db_fetch_cell_prepared('SELECT acquired_at FROM plugin_cloud_lease WHERE account_id = ?', [$accountId], '', true, $this->connection); + return (int) db_fetch_cell_prepared( + 'SELECT acquired_at FROM plugin_cloud_lease WHERE account_id = ?', + [$accountId], + '', + true, + $this->connection + ); } public function release(int $accountId, string $holder): void { - db_execute_prepared('UPDATE plugin_cloud_lease SET expires_at = 0 WHERE account_id = ? AND holder = ?', [$accountId, $holder], true, $this->connection); + db_execute_prepared( + 'UPDATE plugin_cloud_lease SET expires_at = 0 WHERE account_id = ? AND holder = ?', + [$accountId, $holder], + true, + $this->connection + ); } } diff --git a/lib/Observation.php b/lib/Observation.php index 0b6152c..92c3e96 100644 --- a/lib/Observation.php +++ b/lib/Observation.php @@ -44,6 +44,12 @@ public static function fromRow(array $row): ?self { return null; } - return new self($resource, $metric, Row::float($row, 'value'), Row::int($row, 'observed_at', 0, 0), Row::int($row, 'fetched_at', 0, 0)); + return new self( + $resource, + $metric, + Row::float($row, 'value'), + Row::int($row, 'observed_at', 0, 0), + Row::int($row, 'fetched_at', 0, 0) + ); } } diff --git a/lib/ObservationRepository.php b/lib/ObservationRepository.php index 64ebbbf..221d365 100644 --- a/lib/ObservationRepository.php +++ b/lib/ObservationRepository.php @@ -32,14 +32,16 @@ public function __construct(private readonly \PDO|false $connection) { } public function write(int $accountId, string $holder, int $now, Observation $observation): void { - db_execute_prepared('INSERT INTO plugin_cloud_observation (resource_id, metric, value, observed_at, fetched_at, status) + db_execute_prepared('INSERT INTO plugin_cloud_observation + (resource_id, metric, value, observed_at, fetched_at, status) SELECT ?, ?, ?, ?, ?, ? FROM plugin_cloud_lease l WHERE l.account_id = ? AND l.holder = ? AND l.expires_at >= ? ON DUPLICATE KEY UPDATE value = IF(VALUES(observed_at) >= observed_at, VALUES(value), value), status = IF(VALUES(observed_at) >= observed_at, VALUES(status), status), fetched_at = IF(VALUES(observed_at) >= observed_at, VALUES(fetched_at), fetched_at), observed_at = GREATEST(observed_at, VALUES(observed_at))', [ - $observation->resourceId, $observation->metric, $observation->value, $observation->observedAt, $observation->fetchedAt, $observation->value === null ? 'unknown' : 'ok', + $observation->resourceId, $observation->metric, $observation->value, $observation->observedAt, + $observation->fetchedAt, $observation->value === null ? 'unknown' : 'ok', $accountId, $holder, $now, ], true, $this->connection); } @@ -52,14 +54,22 @@ public function write(int $accountId, string $holder, int $now, Observation $obs */ public function markUnread(int $accountId, string $holder, int $now, array $requests, string $reason): void { foreach ($requests as $request) { - db_execute_prepared('INSERT INTO plugin_cloud_observation (resource_id, metric, value, observed_at, fetched_at, status) + db_execute_prepared('INSERT INTO plugin_cloud_observation + (resource_id, metric, value, observed_at, fetched_at, status) SELECT ?, ?, NULL, 0, ?, ? FROM plugin_cloud_lease l WHERE l.account_id = ? AND l.holder = ? AND l.expires_at >= ? - ON DUPLICATE KEY UPDATE status = VALUES(status)', [$request->resourceId, $request->metric, $now, $reason, $accountId, $holder, $now], true, $this->connection); + ON DUPLICATE KEY UPDATE status = VALUES(status)', [ + $request->resourceId, $request->metric, $now, $reason, $accountId, $holder, $now, + ], true, $this->connection); } } public function find(int $resourceId, string $metric): ?Observation { - $row = db_fetch_row_prepared('SELECT * FROM plugin_cloud_observation WHERE resource_id = ? AND metric = ?', [$resourceId, $metric], true, $this->connection); + $row = db_fetch_row_prepared( + 'SELECT * FROM plugin_cloud_observation WHERE resource_id = ? AND metric = ?', + [$resourceId, $metric], + true, + $this->connection + ); return is_array($row) ? Observation::fromRow($row) : null; } @@ -70,7 +80,13 @@ public function find(int $resourceId, string $metric): ?Observation { public function forAccount(int $accountId): array { $out = []; - foreach (Row::rows(db_fetch_assoc_prepared('SELECT o.* FROM plugin_cloud_observation o INNER JOIN plugin_cloud_resource r ON r.id = o.resource_id WHERE r.account_id = ?', [$accountId], true, $this->connection)) as $row) { + foreach (Row::rows(db_fetch_assoc_prepared( + 'SELECT o.* FROM plugin_cloud_observation o INNER JOIN plugin_cloud_resource r ON r.id = o.resource_id + WHERE r.account_id = ?', + [$accountId], + true, + $this->connection + )) as $row) { $observation = Observation::fromRow($row); if ($observation !== null) { diff --git a/lib/Operation.php b/lib/Operation.php index 0ce8a71..9b12ff4 100644 --- a/lib/Operation.php +++ b/lib/Operation.php @@ -53,7 +53,10 @@ public function matches(HttpRequest $request): bool { $query = $parts['query'] ?? ''; - if ($query !== '' && ($this->queryPattern === null || self::repeatsName($query) || preg_match($this->queryPattern, $query) !== 1)) { + if ( + $query !== '' + && ($this->queryPattern === null || self::repeatsName($query) || preg_match($this->queryPattern, $query) !== 1) + ) { return false; } diff --git a/lib/Redactor.php b/lib/Redactor.php index b48e5d2..aee3a08 100644 --- a/lib/Redactor.php +++ b/lib/Redactor.php @@ -56,10 +56,13 @@ public function add(Secret $secret): void { * Each pattern masks its named group "v", or the whole match without one. */ private const PATTERNS = [ - '/\b(?:authorization|proxy-authorization|x-amz-security-token|x-goog-iam-authorization-token|cookie|set-cookie)\s*:\s*(?[^\r\n]*)/i', + '/\b(?:authorization|proxy-authorization|x-amz-security-token|x-goog-iam-authorization-token|' + . 'cookie|set-cookie)\s*:\s*(?[^\r\n]*)/i', '/\b(?:bearer|basic)\s+(?[A-Za-z0-9._~+\/=-]+)/i', - '/\b(?:X-Amz-Signature|X-Amz-Credential|X-Amz-Security-Token|signature|access_token|refresh_token|client_secret|assertion)=(?[^&\s"]*)/i', - '/"(?:access_token|refresh_token|id_token|client_secret|private_key|secret_access_key|session_token)"\s*:\s*"(?(?:[^"\\\\]|\\\\.)*)"/i', + '/\b(?:X-Amz-Signature|X-Amz-Credential|X-Amz-Security-Token|signature|access_token|refresh_token|' + . 'client_secret|assertion)=(?[^&\s"]*)/i', + '/"(?:access_token|refresh_token|id_token|client_secret|private_key|secret_access_key|session_token)"' + . '\s*:\s*"(?(?:[^"\\\\]|\\\\.)*)"/i', '/-----BEGIN [A-Z ]*PRIVATE KEY-----.*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/s', ]; diff --git a/lib/ResourceRepository.php b/lib/ResourceRepository.php index 58bb74e..119e9c3 100644 --- a/lib/ResourceRepository.php +++ b/lib/ResourceRepository.php @@ -41,9 +41,15 @@ public function sync(int $accountId, Inventory $inventory, LeaseRepository $leas return false; } - db_execute_prepared('INSERT INTO plugin_cloud_resource (account_id, type, provider_id, name, region, lifecycle, missing_count, first_seen, last_seen) - SELECT ?, ?, ?, ?, ?, ?, 0, ?, ? FROM plugin_cloud_lease l WHERE l.account_id = ? AND l.holder = ? AND l.expires_at >= ? - ON DUPLICATE KEY UPDATE name = VALUES(name), region = VALUES(region), lifecycle = VALUES(lifecycle), missing_count = 0, last_seen = VALUES(last_seen)', [$accountId, $resource->type, $resource->providerId, $resource->name, $resource->region, Lifecycle::Active->value, $now, $now, $accountId, $holder, $now], true, $this->connection); + db_execute_prepared('INSERT INTO plugin_cloud_resource + (account_id, type, provider_id, name, region, lifecycle, missing_count, first_seen, last_seen) + SELECT ?, ?, ?, ?, ?, ?, 0, ?, ? FROM plugin_cloud_lease l + WHERE l.account_id = ? AND l.holder = ? AND l.expires_at >= ? + ON DUPLICATE KEY UPDATE name = VALUES(name), region = VALUES(region), lifecycle = VALUES(lifecycle), + missing_count = 0, last_seen = VALUES(last_seen)', [ + $accountId, $resource->type, $resource->providerId, $resource->name, $resource->region, + Lifecycle::Active->value, $now, $now, $accountId, $holder, $now, + ], true, $this->connection); $seen[] = $resource->type . "\0" . $resource->providerId; } @@ -52,15 +58,25 @@ public function sync(int $accountId, Inventory $inventory, LeaseRepository $leas return false; } - foreach (Row::rows(db_fetch_assoc_prepared('SELECT id, type, provider_id, missing_count FROM plugin_cloud_resource WHERE account_id = ? AND lifecycle != ?', [$accountId, Lifecycle::Deleted->value], true, $this->connection)) as $row) { + foreach (Row::rows(db_fetch_assoc_prepared( + 'SELECT id, type, provider_id, missing_count FROM plugin_cloud_resource WHERE account_id = ? AND lifecycle != ?', + [$accountId, Lifecycle::Deleted->value], + true, + $this->connection + )) as $row) { if (in_array(Row::string($row, 'type') . "\0" . Row::string($row, 'provider_id'), $seen, true)) { continue; } $missing = Row::int($row, 'missing_count', 0, 0) + 1; - db_execute_prepared('UPDATE plugin_cloud_resource r INNER JOIN plugin_cloud_lease l ON l.account_id = r.account_id AND l.holder = ? AND l.expires_at >= ? - SET r.missing_count = ?, r.lifecycle = ? WHERE r.id = ?', [$holder, $now, $missing, ($missing >= self::DELETE_AFTER ? Lifecycle::Deleted : Lifecycle::Missing)->value, Row::int($row, 'id')], true, $this->connection); + db_execute_prepared('UPDATE plugin_cloud_resource r INNER JOIN plugin_cloud_lease l + ON l.account_id = r.account_id AND l.holder = ? AND l.expires_at >= ? + SET r.missing_count = ?, r.lifecycle = ? WHERE r.id = ?', [ + $holder, $now, $missing, + ($missing >= self::DELETE_AFTER ? Lifecycle::Deleted : Lifecycle::Missing)->value, + Row::int($row, 'id'), + ], true, $this->connection); } return true; @@ -72,7 +88,12 @@ public function sync(int $accountId, Inventory $inventory, LeaseRepository $leas public function counts(int $accountId): array { $counts = []; - foreach (Row::rows(db_fetch_assoc_prepared('SELECT lifecycle, COUNT(*) AS n FROM plugin_cloud_resource WHERE account_id = ? GROUP BY lifecycle', [$accountId], true, $this->connection)) as $row) { + foreach (Row::rows(db_fetch_assoc_prepared( + 'SELECT lifecycle, COUNT(*) AS n FROM plugin_cloud_resource WHERE account_id = ? GROUP BY lifecycle', + [$accountId], + true, + $this->connection + )) as $row) { $counts[Row::string($row, 'lifecycle')] = Row::int($row, 'n'); } diff --git a/lib/Schema.php b/lib/Schema.php index 447d23e..26bbad5 100644 --- a/lib/Schema.php +++ b/lib/Schema.php @@ -50,7 +50,13 @@ public function __construct(private readonly \PDO|false $connection) { } public function storedVersion(): int { - $value = db_fetch_cell_prepared('SELECT value FROM settings WHERE name = ?', [self::SETTING], '', true, $this->connection); + $value = db_fetch_cell_prepared( + 'SELECT value FROM settings WHERE name = ?', + [self::SETTING], + '', + true, + $this->connection + ); return is_numeric($value) ? (int) $value : 0; } @@ -85,7 +91,12 @@ public function migrate(int $through = self::VERSION): bool { return false; } - db_execute_prepared('REPLACE INTO settings (name, value) VALUES (?, ?)', [self::SETTING, (string) $version], true, $this->connection); + db_execute_prepared( + 'REPLACE INTO settings (name, value) VALUES (?, ?)', + [self::SETTING, (string) $version], + true, + $this->connection + ); Log::info(sprintf('Schema migrated to version %d', $version)); } @@ -94,18 +105,41 @@ public function migrate(int $through = self::VERSION): bool { } public function recordedPluginVersion(): string { - return (string) db_fetch_cell_prepared('SELECT version FROM plugin_config WHERE directory = ?', [self::PLUGIN], '', true, $this->connection); + return (string) db_fetch_cell_prepared( + 'SELECT version FROM plugin_config WHERE directory = ?', + [self::PLUGIN], + '', + true, + $this->connection + ); } public function recordPluginVersion(string $version, string $author, string $homepage): void { - db_execute_prepared('UPDATE plugin_config SET version = ?, author = ?, webpage = ? WHERE directory = ?', [$version, $author, $homepage, self::PLUGIN], true, $this->connection); + db_execute_prepared( + 'UPDATE plugin_config SET version = ?, author = ?, webpage = ? WHERE directory = ?', + [$version, $author, $homepage, self::PLUGIN], + true, + $this->connection + ); } public function hooksRegistered(): bool { $placeholders = implode(', ', array_fill(0, count(self::HOOKS), '?')); - $hooks = (int) db_fetch_cell_prepared("SELECT COUNT(DISTINCT hook) FROM plugin_hooks WHERE name = ? AND hook IN ($placeholders)", array_merge([self::PLUGIN], array_keys(self::HOOKS)), '', true, $this->connection); - $realms = (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_realms WHERE plugin = ?', [self::PLUGIN], '', true, $this->connection); + $hooks = (int) db_fetch_cell_prepared( + "SELECT COUNT(DISTINCT hook) FROM plugin_hooks WHERE name = ? AND hook IN ($placeholders)", + array_merge([self::PLUGIN], array_keys(self::HOOKS)), + '', + true, + $this->connection + ); + $realms = (int) db_fetch_cell_prepared( + 'SELECT COUNT(*) FROM plugin_realms WHERE plugin = ?', + [self::PLUGIN], + '', + true, + $this->connection + ); return $hooks === count(self::HOOKS) && $realms === count(Pages::realms()); } @@ -115,7 +149,12 @@ public function hooksRegistered(): bool { * schema version so a reinstall reuses them. */ public function untrackTables(): void { - db_execute_prepared("DELETE FROM plugin_db_changes WHERE plugin = ? AND method = 'create'", [self::PLUGIN], true, $this->connection); + db_execute_prepared( + "DELETE FROM plugin_db_changes WHERE plugin = ? AND method = 'create'", + [self::PLUGIN], + true, + $this->connection + ); } public function forgetVersion(): void { @@ -142,7 +181,13 @@ private function migrations(): array { public function trackTables(): void { foreach (array_keys(self::tables()) as $table) { if ($this->tableExists($table)) { - db_execute_prepared("INSERT INTO plugin_db_changes (plugin, `table`, `column`, `method`) SELECT ?, ?, '', 'create' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM plugin_db_changes WHERE plugin = ? AND `table` = ? AND `method` = 'create')", [self::PLUGIN, $table, self::PLUGIN, $table], true, $this->connection); + db_execute_prepared( + "INSERT INTO plugin_db_changes (plugin, `table`, `column`, `method`) SELECT ?, ?, '', 'create' FROM DUAL + WHERE NOT EXISTS (SELECT 1 FROM plugin_db_changes WHERE plugin = ? AND `table` = ? AND `method` = 'create')", + [self::PLUGIN, $table, self::PLUGIN, $table], + true, + $this->connection + ); } } } @@ -165,7 +210,13 @@ private function createTables(array $tables): bool { } private function tableExists(string $table): bool { - return db_fetch_cell_prepared('SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', [$table], '', true, $this->connection) > 0; + return db_fetch_cell_prepared( + 'SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', + [$table], + '', + true, + $this->connection + ) > 0; } /** @@ -177,10 +228,31 @@ private function tableExists(string $table): bool { * @return array> */ public static function tables(): array { - $innodb = ['type' => 'InnoDB', 'charset' => 'utf8mb4', 'collate' => 'utf8mb4_unicode_ci', 'row_format' => 'Dynamic']; - $id = static fn (string $name): array => ['name' => $name, 'type' => 'int(10)', 'unsigned' => true, 'NULL' => false]; - $time = static fn (string $name): array => ['name' => $name, 'type' => 'int(10)', 'unsigned' => true, 'NULL' => false, 'default' => '0']; - $text = static fn (string $name, int $length, string $default = ''): array => ['name' => $name, 'type' => "varchar($length)", 'NULL' => false, 'default' => $default]; + $innodb = [ + 'type' => 'InnoDB', + 'charset' => 'utf8mb4', + 'collate' => 'utf8mb4_unicode_ci', + 'row_format' => 'Dynamic' + ]; + $id = static fn (string $name): array => [ + 'name' => $name, + 'type' => 'int(10)', + 'unsigned' => true, + 'NULL' => false + ]; + $time = static fn (string $name): array => [ + 'name' => $name, + 'type' => 'int(10)', + 'unsigned' => true, + 'NULL' => false, + 'default' => '0' + ]; + $text = static fn (string $name, int $length, string $default = ''): array => [ + 'name' => $name, + 'type' => "varchar($length)", + 'NULL' => false, + 'default' => $default + ]; return [ 'plugin_cloud_account' => $innodb + [ diff --git a/lib/SecretRepository.php b/lib/SecretRepository.php index 1a02535..db262c2 100644 --- a/lib/SecretRepository.php +++ b/lib/SecretRepository.php @@ -29,20 +29,51 @@ public function __construct(private readonly \PDO|false $connection, private rea } public function load(int $accountId, string $purpose): ?VaultEntry { - $row = db_fetch_row_prepared('SELECT nonce, ciphertext, tag, key_id, expires_at FROM plugin_cloud_secret WHERE account_id = ? AND purpose = ?', [$accountId, $purpose], true, $this->connection); + $row = db_fetch_row_prepared( + 'SELECT nonce, ciphertext, tag, key_id, expires_at FROM plugin_cloud_secret WHERE account_id = ? AND purpose = ?', + [$accountId, $purpose], + true, + $this->connection + ); return is_array($row) ? VaultEntry::fromRow($row) : null; } public function store(int $accountId, string $purpose, VaultEntry $entry): bool { - return (bool) db_execute_prepared('REPLACE INTO plugin_cloud_secret (account_id, purpose, nonce, ciphertext, tag, key_id, expires_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', [$accountId, $purpose, $entry->nonce, $entry->ciphertext, $entry->tag, $entry->keyId, $entry->expiresAt, $this->clock->now()], true, $this->connection); + return (bool) db_execute_prepared( + 'REPLACE INTO plugin_cloud_secret (account_id, purpose, nonce, ciphertext, tag, key_id, expires_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)', + [ + $accountId, + $purpose, + $entry->nonce, + $entry->ciphertext, + $entry->tag, + $entry->keyId, + $entry->expiresAt, + $this->clock->now() + ], + true, + $this->connection + ); } public function has(int $accountId, string $purpose): bool { - return (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_cloud_secret WHERE account_id = ? AND purpose = ?', [$accountId, $purpose], '', true, $this->connection) > 0; + return (int) db_fetch_cell_prepared( + 'SELECT COUNT(*) FROM plugin_cloud_secret WHERE account_id = ? AND purpose = ?', + [$accountId, $purpose], + '', + true, + $this->connection + ) > 0; } public function delete(int $accountId, string $purpose): void { - db_execute_prepared('DELETE FROM plugin_cloud_secret WHERE account_id = ? AND purpose = ?', [$accountId, $purpose], true, $this->connection); + db_execute_prepared( + 'DELETE FROM plugin_cloud_secret WHERE account_id = ? AND purpose = ?', + [$accountId, $purpose], + true, + $this->connection + ); } } diff --git a/lib/SecureFile.php b/lib/SecureFile.php index 96517ad..73ea7ca 100644 --- a/lib/SecureFile.php +++ b/lib/SecureFile.php @@ -28,7 +28,12 @@ */ final class SecureFile { public static function pathAcceptable(string $path): bool { - return $path !== '' && strlen($path) <= 512 && $path[0] === '/' && preg_match('/[\x00-\x1f\x7f]/', $path) !== 1 && !str_contains($path, '/../') && !str_ends_with($path, '/..'); + return $path !== '' + && strlen($path) <= 512 + && $path[0] === '/' + && preg_match('/[\x00-\x1f\x7f]/', $path) !== 1 + && !str_contains($path, '/../') + && !str_ends_with($path, '/..'); } /** diff --git a/lib/SeriesRepository.php b/lib/SeriesRepository.php index e08ba86..056926c 100644 --- a/lib/SeriesRepository.php +++ b/lib/SeriesRepository.php @@ -41,7 +41,12 @@ public function enabledFor(int $accountId): array { ORDER BY s.resource_id, s.metric", [$accountId, Lifecycle::Active->value], true, $this->connection); foreach (Row::rows($rows) as $row) { - $requests[] = new MetricRequest(Row::int($row, 'resource_id'), Row::string($row, 'type'), Row::string($row, 'provider_id'), Row::string($row, 'metric')); + $requests[] = new MetricRequest( + Row::int($row, 'resource_id'), + Row::string($row, 'type'), + Row::string($row, 'provider_id'), + Row::string($row, 'metric') + ); } return $requests; diff --git a/lib/Settings.php b/lib/Settings.php index 595b749..9e8588d 100644 --- a/lib/Settings.php +++ b/lib/Settings.php @@ -55,7 +55,10 @@ public static function fromRow(array $row): self { return new self( vaultKeyFile: $keyFile === '' ? self::DEFAULT_KEY_FILE : $keyFile, collectorBudget: min(Row::int($row, 'cloud_collector_budget', self::DEFAULT_BUDGET, 10), 3600), - keepTablesOnUninstall: array_key_exists('cloud_uninstall_keep_tables', $row) ? Row::bool($row, 'cloud_uninstall_keep_tables') : true, + keepTablesOnUninstall: array_key_exists('cloud_uninstall_keep_tables', $row) ? Row::bool( + $row, + 'cloud_uninstall_keep_tables' + ) : true, ); } @@ -76,7 +79,10 @@ public static function form(): array { ], 'cloud_vault_key_file' => [ 'friendly_name' => __('Vault Key File', 'cloud'), - 'description' => __('Absolute path to the 32-byte key that encrypts stored credentials. Create it yourself, outside the web root, readable only by the web server and poller user, in a directory that only root and that user can write (the same applies to credential files); the plugin never creates or writes it. Back it up with the database: without it, stored credentials must be entered again.', 'cloud'), + 'description' => __( + 'Absolute path to the 32-byte key that encrypts stored credentials. Create it yourself, outside the web root, readable only by the web server and poller user, in a directory that only root and that user can write (the same applies to credential files); the plugin never creates or writes it. Back it up with the database: without it, stored credentials must be entered again.', + 'cloud' + ), 'method' => 'textbox', 'default' => self::DEFAULT_KEY_FILE, 'max_length' => '255', @@ -88,7 +94,10 @@ public static function form(): array { ], 'cloud_collector_budget' => [ 'friendly_name' => __('Collector Time Budget', 'cloud'), - 'description' => __('Seconds one collector run may spend before it stops starting new work. Keep it below the poller interval; unfinished accounts resume on the next run.', 'cloud'), + 'description' => __( + 'Seconds one collector run may spend before it stops starting new work. Keep it below the poller interval; unfinished accounts resume on the next run.', + 'cloud' + ), 'method' => 'textbox', 'default' => (string) self::DEFAULT_BUDGET, 'filter' => FILTER_VALIDATE_INT, @@ -102,7 +111,10 @@ public static function form(): array { ], 'cloud_uninstall_keep_tables' => [ 'friendly_name' => __('Keep Plugin Tables on Uninstall', 'cloud'), - 'description' => __('When checked, uninstalling the plugin keeps its accounts, encrypted credentials, and cache. Clear it to have the uninstall drop them. Cloud resources are never touched either way.', 'cloud'), + 'description' => __( + 'When checked, uninstalling the plugin keeps its accounts, encrypted credentials, and cache. Clear it to have the uninstall drop them. Cloud resources are never touched either way.', + 'cloud' + ), 'method' => 'checkbox', 'default' => 'on', ], diff --git a/lib/SettingsRepository.php b/lib/SettingsRepository.php index 11c3ee3..020ad22 100644 --- a/lib/SettingsRepository.php +++ b/lib/SettingsRepository.php @@ -36,7 +36,12 @@ public function load(): Settings { $placeholders = implode(', ', array_fill(0, count(Settings::NAMES), '?')); $row = []; - foreach (Row::rows(db_fetch_assoc_prepared("SELECT name, value FROM settings WHERE name IN ($placeholders)", Settings::NAMES, true, $this->connection)) as $setting) { + foreach (Row::rows(db_fetch_assoc_prepared( + "SELECT name, value FROM settings WHERE name IN ($placeholders)", + Settings::NAMES, + true, + $this->connection + )) as $setting) { $row[Row::string($setting, 'name')] = $setting['value'] ?? null; } diff --git a/lib/SocketTransport.php b/lib/SocketTransport.php index 4bf1328..f410e6f 100644 --- a/lib/SocketTransport.php +++ b/lib/SocketTransport.php @@ -60,7 +60,8 @@ public function send(HttpRequest $request): HttpResponse { // A CR or LF in a name or value would let a caller inject headers or a // second request. - $request = "$method $target HTTP/1.1\r\nHost: " . $host . ($port === 443 ? '' : ":$port") . "\r\nConnection: close\r\n"; + $request = "$method $target HTTP/1.1\r\nHost: " . $host . ($port === 443 ? '' : ":$port") + . "\r\nConnection: close\r\n"; foreach ($headers as $name => $value) { if (preg_match('/^[!#$%&\'*+.^_`|~0-9A-Za-z-]+$/', $name) !== 1 || preg_match('/[\r\n\x00]/', $value) === 1) { throw new TransportError('header_rejected'); @@ -260,7 +261,11 @@ private static function dechunk(string $raw): string { $pos = 0; while (true) { $eol = strpos($raw, "\r\n", $pos); - if ($eol === false || preg_match('/^([0-9A-Fa-f]{1,8})(?:;[^\r\n]*)?$/', substr($raw, $pos, $eol - $pos), $m) !== 1) { + if ($eol === false || preg_match( + '/^([0-9A-Fa-f]{1,8})(?:;[^\r\n]*)?$/', + substr($raw, $pos, $eol - $pos), + $m + ) !== 1) { throw new TransportError('malformed', 'chunk size'); } // At most eight hex digits, so the value always fits an int. diff --git a/lib/TransportError.php b/lib/TransportError.php index afd6ca1..207be2b 100644 --- a/lib/TransportError.php +++ b/lib/TransportError.php @@ -31,7 +31,13 @@ public function __construct(public readonly string $kind, string $detail = '') { public function errorClass(): ErrorClass { return match ($this->kind) { - 'url_rejected', 'host_refused', 'operation_refused', 'header_rejected', 'redirect_refused', 'tls_verify', 'tls_name' => ErrorClass::Config, + 'url_rejected', + 'host_refused', + 'operation_refused', + 'header_rejected', + 'redirect_refused', + 'tls_verify', + 'tls_name' => ErrorClass::Config, 'malformed', 'too_large', 'headers_too_large' => ErrorClass::Malformed, default => ErrorClass::Transient, }; diff --git a/lib/Vault.php b/lib/Vault.php index b600676..2033072 100644 --- a/lib/Vault.php +++ b/lib/Vault.php @@ -40,7 +40,16 @@ public function encrypt(Secret $secret, int $accountId, string $purpose, int $ex $nonce = random_bytes(self::NONCE_BYTES); $tag = ''; - $ciphertext = openssl_encrypt($secret->reveal(), self::CIPHER, $this->key->bytes(), OPENSSL_RAW_DATA, $nonce, $tag, self::additionalData($accountId, $purpose), self::TAG_BYTES); + $ciphertext = openssl_encrypt( + $secret->reveal(), + self::CIPHER, + $this->key->bytes(), + OPENSSL_RAW_DATA, + $nonce, + $tag, + self::additionalData($accountId, $purpose), + self::TAG_BYTES + ); if ($ciphertext === false || strlen($tag) !== self::TAG_BYTES) { throw CredentialError::because('the credential could not be encrypted'); @@ -57,7 +66,15 @@ public function decrypt(VaultEntry $entry, int $accountId, string $purpose): Sec throw CredentialError::because('the credential was stored with a different vault key; enter it again'); } - $plain = openssl_decrypt($entry->ciphertext, self::CIPHER, $this->key->bytes(), OPENSSL_RAW_DATA, $entry->nonce, $entry->tag, self::additionalData($accountId, $purpose)); + $plain = openssl_decrypt( + $entry->ciphertext, + self::CIPHER, + $this->key->bytes(), + OPENSSL_RAW_DATA, + $entry->nonce, + $entry->tag, + self::additionalData($accountId, $purpose) + ); if ($plain === false) { throw CredentialError::because('the stored credential failed its integrity check'); diff --git a/lib/VaultEntry.php b/lib/VaultEntry.php index a533820..72630dd 100644 --- a/lib/VaultEntry.php +++ b/lib/VaultEntry.php @@ -40,7 +40,13 @@ public static function fromRow(array $row): ?self { $ciphertext = $row['ciphertext'] ?? null; $tag = $row['tag'] ?? null; - if (!is_string($nonce) || strlen($nonce) !== Vault::NONCE_BYTES || !is_string($ciphertext) || !is_string($tag) || strlen($tag) !== Vault::TAG_BYTES) { + if ( + !is_string($nonce) + || strlen($nonce) !== Vault::NONCE_BYTES + || !is_string($ciphertext) + || !is_string($tag) + || strlen($tag) !== Vault::TAG_BYTES + ) { return null; } diff --git a/lib/VerifyStatus.php b/lib/VerifyStatus.php index 3342adb..a781f50 100644 --- a/lib/VerifyStatus.php +++ b/lib/VerifyStatus.php @@ -50,7 +50,10 @@ public function message(): string { self::Ok => __('The credential works and has the permissions this account needs.', 'cloud'), self::Invalid => __('The provider rejected the credential. It may be wrong, expired, or revoked.', 'cloud'), self::Permission => __('The credential works but lacks a permission this account needs.', 'cloud'), - self::Unreachable => __('The provider could not be reached. Check the network path and outbound policy from the poller.', 'cloud'), + self::Unreachable => __( + 'The provider could not be reached. Check the network path and outbound policy from the poller.', + 'cloud' + ), self::Throttled => __('The provider is throttling requests. Try again later.', 'cloud'), self::Malformed => __('The provider sent a response the plugin could not read.', 'cloud'), self::Config => __('The account or its credential is not configured correctly.', 'cloud'), diff --git a/locales/po/cacti.pot b/locales/po/cacti.pot index 3a468bd..91eb429 100644 --- a/locales/po/cacti.pot +++ b/locales/po/cacti.pot @@ -107,14 +107,6 @@ msgstr "" msgid "Cloud Accounts" msgstr "" -#: lib/AccountsPage.php -msgid "Actions" -msgstr "" - -#: lib/AccountsPage.php lib/HealthPage.php -msgid "Credential" -msgstr "" - #: lib/AccountsPage.php msgid "Name" msgstr "" @@ -123,6 +115,10 @@ msgstr "" msgid "Provider" msgstr "" +#: lib/AccountsPage.php lib/HealthPage.php +msgid "Credential" +msgstr "" + #: lib/AccountsPage.php msgid "State" msgstr "" @@ -131,6 +127,10 @@ msgstr "" msgid "Verify" msgstr "" +#: lib/AccountsPage.php +msgid "Actions" +msgstr "" + #: lib/AccountsPage.php lib/HealthPage.php msgid "No cloud accounts yet." msgstr "" @@ -185,11 +185,11 @@ msgid "Save" msgstr "" #: lib/AccountsPage.php -msgid "None stored" +msgid "Stored in the vault" msgstr "" #: lib/AccountsPage.php -msgid "Stored in the vault" +msgid "None stored" msgstr "" #: lib/AccountsPage.php @@ -233,19 +233,19 @@ msgid "Collection" msgstr "" #: lib/HealthPage.php -msgid "Data" +msgid "Last Run" msgstr "" #: lib/HealthPage.php -msgid "Discovery" +msgid "Series Read" msgstr "" #: lib/HealthPage.php -msgid "Last Run" +msgid "Requests" msgstr "" #: lib/HealthPage.php -msgid "Requests" +msgid "Discovery" msgstr "" #: lib/HealthPage.php @@ -253,7 +253,7 @@ msgid "Resources" msgstr "" #: lib/HealthPage.php -msgid "Series Read" +msgid "Data" msgstr "" #: lib/HealthPage.php diff --git a/poller_cloud.php b/poller_cloud.php index bc4c5d5..33428cc 100644 --- a/poller_cloud.php +++ b/poller_cloud.php @@ -45,7 +45,11 @@ } elseif ($cloud_arg === '--debug') { $debug = true; } else { - fwrite(STDERR, 'ERROR: Unknown argument ' . $cloud_arg . PHP_EOL . 'usage: poller_cloud.php [--poller=N] [--force] [--debug]' . PHP_EOL); + fwrite( + STDERR, + 'ERROR: Unknown argument ' . $cloud_arg . PHP_EOL + . 'usage: poller_cloud.php [--poller=N] [--force] [--debug]' . PHP_EOL + ); exit(1); } } @@ -65,14 +69,24 @@ } if (!(new \Somethingwithproof\Cloud\Schema(false))->isCurrent()) { - cacti_log('ERROR: The cloud collector did not run because the plugin schema is not current; open the Plugins page to finish the upgrade', false, 'CLOUD'); + cacti_log( + 'ERROR: The cloud collector did not run because the plugin schema is not current; ' + . 'open the Plugins page to finish the upgrade', + false, + 'CLOUD' + ); exit(1); } $cloud_budget = cloud_settings()->collectorBudget; if (!register_process_start('cloud', 'collector', $cloud_poller, $cloud_budget + 120)) { - cacti_log('NOTE: A cloud collector is already running on poller ' . $cloud_poller, false, 'CLOUD', POLLER_VERBOSITY_MEDIUM); + cacti_log( + 'NOTE: A cloud collector is already running on poller ' . $cloud_poller, + false, + 'CLOUD', + POLLER_VERBOSITY_MEDIUM + ); exit(0); } @@ -82,6 +96,17 @@ unregister_process('cloud', 'collector', $cloud_poller); } -cacti_log(sprintf('STATS: Poller:%d Accounts:%d Skipped:%d StoppedEarly:%s', $cloud_poller, $cloud_result['accounts'], $cloud_result['skipped'], $cloud_result['stopped_early'] ? 'yes' : 'no'), false, 'CLOUD', POLLER_VERBOSITY_MEDIUM); +cacti_log( + sprintf( + 'STATS: Poller:%d Accounts:%d Skipped:%d StoppedEarly:%s', + $cloud_poller, + $cloud_result['accounts'], + $cloud_result['skipped'], + $cloud_result['stopped_early'] ? 'yes' : 'no' + ), + false, + 'CLOUD', + POLLER_VERBOSITY_MEDIUM +); exit(0); diff --git a/setup.php b/setup.php index 309d54c..4dbece9 100644 --- a/setup.php +++ b/setup.php @@ -75,9 +75,18 @@ function cloud_boot(): bool { */ function cloud_refuse_unsupported(): bool { if (!cloud_php_supported()) { - $message = __('The Cloud plugin requires PHP %s or later. This server runs PHP %s, so the plugin was not installed or enabled.', '8.2.0', PHP_VERSION, 'cloud'); + $message = __( + 'The Cloud plugin requires PHP %s or later. This server runs PHP %s, so the plugin was not installed or enabled.', + '8.2.0', + PHP_VERSION, + 'cloud' + ); } elseif (cloud_missing_extensions() !== array()) { - $message = __('The Cloud plugin requires the PHP extensions %s, which this server does not load, so the plugin was not installed or enabled.', implode(', ', cloud_missing_extensions()), 'cloud'); + $message = __( + 'The Cloud plugin requires the PHP extensions %s, which this server does not load, so the plugin was not installed or enabled.', + implode(', ', cloud_missing_extensions()), + 'cloud' + ); } else { return false; } @@ -142,7 +151,11 @@ function cloud_page_start(): bool { html_start_box(__('Cloud', 'cloud'), '100%', '', '3', 'center', ''); - print '' . html_escape(cloud_php_supported() ? __('The Cloud plugin is not enabled.', 'cloud') : __('The Cloud plugin requires PHP %s or later.', '8.2.0', 'cloud')) . ''; + print '' . html_escape( + cloud_php_supported() + ? __('The Cloud plugin is not enabled.', 'cloud') + : __('The Cloud plugin requires PHP %s or later.', '8.2.0', 'cloud') + ) . ''; html_end_box(); @@ -167,7 +180,10 @@ function cloud_require_post(string $page, array $actions): void { } function cloud_credentials(): \Somethingwithproof\Cloud\CredentialStore { - return new \Somethingwithproof\Cloud\CredentialStore(new \Somethingwithproof\Cloud\SecretRepository(false, new \Somethingwithproof\Cloud\SystemClock()), cloud_settings()->vaultKeyFile); + return new \Somethingwithproof\Cloud\CredentialStore( + new \Somethingwithproof\Cloud\SecretRepository(false, new \Somethingwithproof\Cloud\SystemClock()), + cloud_settings()->vaultKeyFile + ); } function cloud_accounts(): \Somethingwithproof\Cloud\AccountRepository { @@ -323,7 +339,12 @@ function cloud_poller_bottom(): void { $php = trim((string) read_config_option('path_php_binary')); if ($php === '' || !is_file($php) || !is_executable($php)) { - cacti_log('ERROR: The cloud collector was not started because the PHP binary path setting is empty or not an executable file', false, 'CLOUD'); + cacti_log( + 'ERROR: The cloud collector was not started because the PHP binary path setting is empty ' + . 'or not an executable file', + false, + 'CLOUD' + ); return; } diff --git a/tests/Integration/LifecycleTest.php b/tests/Integration/LifecycleTest.php index 75f57d7..7129520 100644 --- a/tests/Integration/LifecycleTest.php +++ b/tests/Integration/LifecycleTest.php @@ -202,7 +202,10 @@ ->and($r['observation']['status'])->toBe('ok') ->and($r['health'])->toEqual(['collection' => 'ok', 'series_total' => '1', 'series_read' => '1']) // No lease, or an older datapoint, never overwrites the cache. - ->and($r['after_foreign_writes'])->toEqual(['value' => $r['observation']['value'], 'observed_at' => $r['observation']['observed_at']]) + ->and($r['after_foreign_writes'])->toEqual([ + 'value' => $r['observation']['value'], + 'observed_at' => $r['observation']['observed_at'] + ]) ->and($r['while_leased'])->toBe(['accounts' => 0, 'skipped' => 1, 'stopped_early' => false]) ->and($r['no_budget'])->toBe(['accounts' => 0, 'skipped' => 0, 'stopped_early' => true]) ->and($r['d2_lifecycle'])->toBe(['missing', 'missing', 'deleted']) @@ -261,5 +264,7 @@ ->and($r['while_leased'])->toBe(['accounts' => 0, 'skipped' => 1, 'stopped_early' => false]) ->and($r['after_expiry'])->toBe(['accounts' => 1, 'skipped' => 0, 'stopped_early' => false]) ->and($r['final']['health'])->toEqual(['run_started' => '1800000420', 'collection' => 'ok', 'series_read' => '1']) - ->and($r['final']['observations'])->toEqual([['metric' => 'cpu', 'value' => '7', 'observed_at' => '1799999940', 'status' => 'ok']]); + ->and($r['final']['observations'])->toEqual([ + ['metric' => 'cpu', 'value' => '7', 'observed_at' => '1799999940', 'status' => 'ok'] + ]); }); diff --git a/tests/Security/SourceRulesTest.php b/tests/Security/SourceRulesTest.php index 9ef94ec..b855e10 100644 --- a/tests/Security/SourceRulesTest.php +++ b/tests/Security/SourceRulesTest.php @@ -38,7 +38,11 @@ function cloud_sources(): array { foreach ($iterator as $file) { $relative = substr($file->getPathname(), strlen(cloud_root()) + 1); - if ($file->getExtension() === 'php' && !str_starts_with($relative, 'tests/') && !str_starts_with($relative, '.git/')) { + if ( + $file->getExtension() === 'php' + && !str_starts_with($relative, 'tests/') + && !str_starts_with($relative, '.git/') + ) { $files[] = $relative; } } @@ -156,10 +160,20 @@ function cloud_entry_points(): array { $core = ['Management']; foreach (cloud_sources() as $file) { - $tokens = array_values(array_filter(PhpToken::tokenize((string) file_get_contents(cloud_root() . '/' . $file)), fn ($t) => !$t->is([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT]))); + $tokens = array_values( + array_filter( + PhpToken::tokenize((string) file_get_contents(cloud_root() . '/' . $file)), + fn ($t) => !$t->is([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT]) + ) + ); foreach ($tokens as $i => $token) { - if (!$token->is(T_STRING) || $token->text !== '__' || ($tokens[$i + 1]->text ?? '') !== '(' || ($tokens[$i - 1]->is(T_FUNCTION))) { + if ( + !$token->is(T_STRING) + || $token->text !== '__' + || ($tokens[$i + 1]->text ?? '') !== '(' + || ($tokens[$i - 1]->is(T_FUNCTION)) + ) { continue; } @@ -192,7 +206,10 @@ function cloud_entry_points(): array { it('ships a translation template containing every plugin string', function () { $pot = (string) file_get_contents(cloud_root() . '/locales/po/cacti.pot'); - foreach (['The Cloud plugin requires PHP %s or later. This server runs PHP %s, so the plugin was not installed or enabled.'] as $msgid) { + foreach ([ + 'The Cloud plugin requires PHP %s or later. This server runs PHP %s, ' + . 'so the plugin was not installed or enabled.' + ] as $msgid) { expect($pot)->toContain('msgid "' . $msgid . '"'); } }); @@ -212,7 +229,8 @@ function cloud_entry_points(): array { foreach (cloud_sources() as $file) { $source = (string) file_get_contents(cloud_root() . '/' . $file); - preg_match_all("/__\\('((?:[^'\\\\]|\\\\.)*)'/", $source, $texts); + // The text may sit on the line after __( when the call is wrapped. + preg_match_all("/__\\(\\s*'((?:[^'\\\\]|\\\\.)*)'/", $source, $texts); foreach ($texts[1] as $text) { expect($text)->not->toMatch('/%[0-9]+\$/', $file); diff --git a/tests/Transport/SocketTransportTest.php b/tests/Transport/SocketTransportTest.php index b34bb69..590a403 100644 --- a/tests/Transport/SocketTransportTest.php +++ b/tests/Transport/SocketTransportTest.php @@ -47,7 +47,11 @@ function cloud_free_port(): int { function cloud_server(array $args): int { $port = cloud_free_port(); - $GLOBALS['__cloud_servers'][] = proc_open(array_merge([PHP_BINARY, CLOUD_SPIKE . '/server.php', $args[0], (string) $port], array_slice($args, 1)), [0 => ['file', '/dev/null', 'r'], 1 => ['file', '/dev/null', 'w'], 2 => ['file', '/dev/null', 'w']], $pipes); + $GLOBALS['__cloud_servers'][] = proc_open( + array_merge([PHP_BINARY, CLOUD_SPIKE . '/server.php', $args[0], (string) $port], array_slice($args, 1)), + [0 => ['file', '/dev/null', 'r'], 1 => ['file', '/dev/null', 'w'], 2 => ['file', '/dev/null', 'w']], + $pipes + ); // A refused probe raises a warning, which the suite treats as a failure. set_error_handler(static fn (): bool => true); @@ -72,7 +76,13 @@ function cloud_server(array $args): int { } function cloud_transport(int $port, float $total = 4.0, int $max = 1048576): SocketTransport { - return new SocketTransport(new OutboundPolicy(['127.0.0.1'], [$port]), 2.0, $total, $max, $GLOBALS['__cloud_certs'] . '/ca.pem'); + return new SocketTransport( + new OutboundPolicy(['127.0.0.1'], [$port]), + 2.0, + $total, + $max, + $GLOBALS['__cloud_certs'] . '/ca.pem' + ); } function cloud_kind(callable $call): string { @@ -89,7 +99,13 @@ function cloud_kind(callable $call): string { $GLOBALS['__cloud_servers'] = []; $GLOBALS['__cloud_certs'] = sys_get_temp_dir() . '/cloud-certs-' . getmypid(); @mkdir($GLOBALS['__cloud_certs'], 0700); - exec(escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg(CLOUD_SPIKE . '/make-certs.php') . ' ' . escapeshellarg($GLOBALS['__cloud_certs']), $out, $rc); + exec( + escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg( + CLOUD_SPIKE . '/make-certs.php' + ) . ' ' . escapeshellarg($GLOBALS['__cloud_certs']), + $out, + $rc + ); if ($rc !== 0) { throw new RuntimeException('make-certs failed'); @@ -104,7 +120,9 @@ function cloud_kind(callable $call): string { it('returns status, headers, and body from a trusted server', function () { $port = cloud_server(['tls', $GLOBALS['__cloud_certs'] . '/good.pem']); - $r = cloud_transport($port)->send(new HttpRequest('GET', "https://127.0.0.1:$port/ok", ['Accept' => 'application/json'])); + $r = cloud_transport($port)->send( + new HttpRequest('GET', "https://127.0.0.1:$port/ok", ['Accept' => 'application/json']) + ); expect($r->status)->toBe(200) ->and($r->body)->toBe('{"ok":true}') @@ -116,7 +134,9 @@ function cloud_kind(callable $call): string { expect(cloud_transport($port)->send(new HttpRequest('HEAD', "https://127.0.0.1:$port/head"))->body)->toBe('') ->and(cloud_transport($port)->send(new HttpRequest('GET', "https://127.0.0.1:$port/no-content"))->status)->toBe(204) - ->and(cloud_kind(fn () => cloud_transport($port)->send(new HttpRequest('GET', "https://127.0.0.1:$port/head"))))->toBe('malformed'); + ->and( + cloud_kind(fn () => cloud_transport($port)->send(new HttpRequest('GET', "https://127.0.0.1:$port/head"))) + )->toBe('malformed'); }); it('decodes chunked bodies, skips 1xx responses, and returns error bodies', function () { @@ -133,15 +153,23 @@ function cloud_kind(callable $call): string { $wrong = cloud_server(['tls', $GLOBALS['__cloud_certs'] . '/wrongname.pem']); $good = cloud_server(['tls', $GLOBALS['__cloud_certs'] . '/good.pem']); - expect(cloud_kind(fn () => cloud_transport($self)->send(new HttpRequest('GET', "https://127.0.0.1:$self/ok"))))->toBe('tls_verify') - ->and(cloud_kind(fn () => cloud_transport($wrong)->send(new HttpRequest('GET', "https://127.0.0.1:$wrong/ok"))))->toBe('tls_name') - ->and(cloud_kind(fn () => cloud_transport($good)->send(new HttpRequest('GET', "https://127.0.0.1:$good/redirect"))))->toBe('redirect_refused'); + expect( + cloud_kind(fn () => cloud_transport($self)->send(new HttpRequest('GET', "https://127.0.0.1:$self/ok"))) + )->toBe('tls_verify') + ->and( + cloud_kind(fn () => cloud_transport($wrong)->send(new HttpRequest('GET', "https://127.0.0.1:$wrong/ok"))) + )->toBe('tls_name') + ->and( + cloud_kind(fn () => cloud_transport($good)->send(new HttpRequest('GET', "https://127.0.0.1:$good/redirect"))) + )->toBe('redirect_refused'); }); it('refuses malformed framing', function (string $path, string $kind) { $port = cloud_server(['tls', $GLOBALS['__cloud_certs'] . '/good.pem']); - expect(cloud_kind(fn () => cloud_transport($port)->send(new HttpRequest('GET', "https://127.0.0.1:$port$path"))))->toBe($kind); + expect( + cloud_kind(fn () => cloud_transport($port)->send(new HttpRequest('GET', "https://127.0.0.1:$port$path"))) + )->toBe($kind); })->with([ ['/bad-terminator', 'malformed'], ['/bad-chunk', 'malformed'], @@ -156,7 +184,9 @@ function cloud_kind(callable $call): string { $port = cloud_server(['tls', $GLOBALS['__cloud_certs'] . '/good.pem']); $start = microtime(true); - expect(cloud_kind(fn () => cloud_transport($port, 2.0)->send(new HttpRequest('GET', "https://127.0.0.1:$port$path"))))->toBe('total_timeout') + expect( + cloud_kind(fn () => cloud_transport($port, 2.0)->send(new HttpRequest('GET', "https://127.0.0.1:$port$path"))) + )->toBe('total_timeout') ->and(microtime(true) - $start)->toBeLessThan(3.5); })->with(['/stall', '/slow-body', '/slow-headers']); @@ -164,14 +194,22 @@ function cloud_kind(callable $call): string { $port = cloud_server(['silent']); $start = microtime(true); - expect(cloud_kind(fn () => cloud_transport($port, 1.5)->send(new HttpRequest('GET', "https://127.0.0.1:$port/ok"))))->toBeIn(['connect_timeout', 'total_timeout', 'open_failed']) + expect( + cloud_kind(fn () => cloud_transport($port, 1.5)->send(new HttpRequest('GET', "https://127.0.0.1:$port/ok"))) + )->toBeIn(['connect_timeout', 'total_timeout', 'open_failed']) ->and(microtime(true) - $start)->toBeLessThan(3.0); }); it('refuses header injection before sending', function () { $port = cloud_server(['tls', $GLOBALS['__cloud_certs'] . '/good.pem']); - expect(cloud_kind(fn () => cloud_transport($port)->send(new HttpRequest('GET', "https://127.0.0.1:$port/echo", ['X-Test' => "a\r\nX-Injected: 1"]))))->toBe('header_rejected'); + expect( + cloud_kind( + fn () => cloud_transport($port)->send( + new HttpRequest('GET', "https://127.0.0.1:$port/echo", ['X-Test' => "a\r\nX-Injected: 1"]) + ) + ) + )->toBe('header_rejected'); }); it('refuses URLs outside the policy without opening a socket', function (string $url, string $kind) { @@ -220,17 +258,82 @@ public function send(HttpRequest $request): \Somethingwithproof\Cloud\HttpRespon $guard->send(new HttpRequest('POST', 'https://api.example.com/', $form, 'Action=GetMetricData&Version=2010-08-01')); $guard->send(new HttpRequest('GET', 'https://api.example.com/v2/droplets?page=2&per_page=200')); - expect(cloud_kind(fn () => $guard->send(new HttpRequest('DELETE', 'https://api.example.com/v2/droplets'))))->toBe('operation_refused') - ->and(cloud_kind(fn () => $guard->send(new HttpRequest('GET', 'https://api.example.com/v2/droplets/1/actions'))))->toBe('operation_refused') - ->and(cloud_kind(fn () => $guard->send(new HttpRequest('POST', 'https://api.example.com/', [], 'Action=PutMetricAlarm'))))->toBe('operation_refused') - ->and(cloud_kind(fn () => $guard->send(new HttpRequest('GET', 'https://api.example.com/v2/droplets', [], 'x'))))->toBe('operation_refused') - ->and(cloud_kind(fn () => $guard->send(new HttpRequest('POST', 'https://api.example.com/', $form, 'Action=GetMetricData&Action=PutMetricAlarm'))))->toBe('operation_refused') - ->and(cloud_kind(fn () => $guard->send(new HttpRequest('POST', 'https://api.example.com/', ['CONTENT-TYPE' => 'Application/X-WWW-Form-Urlencoded; charset=utf-8'], 'Action=GetMetricData&Action=PutMetricAlarm'))))->toBe('operation_refused') - ->and(cloud_kind(fn () => $guard->send(new HttpRequest('POST', 'https://api.example.com/', $form + ['CONTENT-TYPE' => 'text/plain'], 'Action=GetMetricData&Action=PutMetricAlarm'))))->toBe('operation_refused') - ->and(cloud_kind(fn () => $guard->send(new HttpRequest('POST', 'https://api.example.com/', $form + ['content-type' => 'application/x-www-form-urlencoded'], 'Action=GetMetricData'))))->toBe('operation_refused') - ->and(cloud_kind(fn () => $guard->send(new HttpRequest('POST', 'https://api.example.com/', $form, 'Action=GetMetricData&action=DeleteAlarms'))))->toBe('operation_refused') - ->and(cloud_kind(fn () => $guard->send(new HttpRequest('POST', 'https://api.example.com/?Action=PutMetricAlarm', $form, 'Action=GetMetricData'))))->toBe('operation_refused') - ->and(cloud_kind(fn () => $guard->send(new HttpRequest('GET', 'https://api.example.com/v2/droplets?page=1&page=2&per_page=1'))))->toBe('operation_refused') - ->and(cloud_kind(fn () => $guard->send(new HttpRequest('GET', 'https://api.example.com/v2/droplets?tag_name=x'))))->toBe('operation_refused') + expect( + cloud_kind(fn () => $guard->send(new HttpRequest('DELETE', 'https://api.example.com/v2/droplets'))) + )->toBe('operation_refused') + ->and( + cloud_kind(fn () => $guard->send(new HttpRequest('GET', 'https://api.example.com/v2/droplets/1/actions'))) + )->toBe('operation_refused') + ->and( + cloud_kind(fn () => $guard->send(new HttpRequest('POST', 'https://api.example.com/', [], 'Action=PutMetricAlarm'))) + )->toBe('operation_refused') + ->and( + cloud_kind(fn () => $guard->send(new HttpRequest('GET', 'https://api.example.com/v2/droplets', [], 'x'))) + )->toBe('operation_refused') + ->and( + cloud_kind( + fn () => $guard->send( + new HttpRequest('POST', 'https://api.example.com/', $form, 'Action=GetMetricData&Action=PutMetricAlarm') + ) + ) + )->toBe('operation_refused') + ->and( + cloud_kind( + fn () => $guard->send( + new HttpRequest( + 'POST', + 'https://api.example.com/', + ['CONTENT-TYPE' => 'Application/X-WWW-Form-Urlencoded; charset=utf-8'], + 'Action=GetMetricData&Action=PutMetricAlarm' + ) + ) + ) + )->toBe('operation_refused') + ->and( + cloud_kind( + fn () => $guard->send( + new HttpRequest( + 'POST', + 'https://api.example.com/', + $form + ['CONTENT-TYPE' => 'text/plain'], + 'Action=GetMetricData&Action=PutMetricAlarm' + ) + ) + ) + )->toBe('operation_refused') + ->and( + cloud_kind( + fn () => $guard->send( + new HttpRequest( + 'POST', + 'https://api.example.com/', + $form + ['content-type' => 'application/x-www-form-urlencoded'], + 'Action=GetMetricData' + ) + ) + ) + )->toBe('operation_refused') + ->and( + cloud_kind( + fn () => $guard->send( + new HttpRequest('POST', 'https://api.example.com/', $form, 'Action=GetMetricData&action=DeleteAlarms') + ) + ) + )->toBe('operation_refused') + ->and( + cloud_kind( + fn () => $guard->send( + new HttpRequest('POST', 'https://api.example.com/?Action=PutMetricAlarm', $form, 'Action=GetMetricData') + ) + ) + )->toBe('operation_refused') + ->and( + cloud_kind( + fn () => $guard->send(new HttpRequest('GET', 'https://api.example.com/v2/droplets?page=1&page=2&per_page=1')) + ) + )->toBe('operation_refused') + ->and( + cloud_kind(fn () => $guard->send(new HttpRequest('GET', 'https://api.example.com/v2/droplets?tag_name=x'))) + )->toBe('operation_refused') ->and($sent->calls)->toBe(3); }); diff --git a/tests/Unit/AccountTest.php b/tests/Unit/AccountTest.php index c920688..d297edc 100644 --- a/tests/Unit/AccountTest.php +++ b/tests/Unit/AccountTest.php @@ -61,8 +61,16 @@ function cloud_account_input(array $override = []): array { 'remote poller' => [['poller_id' => '2'], 'poller_id', 'Poller'], 'unknown source' => [['credential_source' => 'env'], 'credential_source', 'Credential Source'], 'instance on DO' => [['credential_source' => 'instance'], 'credential_source', 'Credential Source'], - 'relative file' => [['credential_source' => 'file', 'credential_file' => 'etc/token'], 'credential_file', 'Credential File'], - 'traversal file' => [['credential_source' => 'file', 'credential_file' => '/etc/../token'], 'credential_file', 'Credential File'], + 'relative file' => [ + ['credential_source' => 'file', 'credential_file' => 'etc/token'], + 'credential_file', + 'Credential File' + ], + 'traversal file' => [ + ['credential_source' => 'file', 'credential_file' => '/etc/../token'], + 'credential_file', + 'Credential File' + ], 'short collect' => [['collect_interval' => '30'], 'collect_interval', 'Collection Interval'], 'text discover' => [['discover_interval' => 'hourly'], 'discover_interval', 'Discovery Interval'], 'zero share' => [['request_share' => '0'], 'request_share', 'Request Share'], @@ -72,16 +80,29 @@ function cloud_account_input(array $override = []): array { it('refuses providers that are not released for new accounts', function () { foreach ([0, -1] as $id) { - expect(AccountInput::parse(cloud_account_input(['provider' => 'aws']), $id, Provider::released())->errors)->toHaveKey('provider'); + expect( + AccountInput::parse(cloud_account_input(['provider' => 'aws']), $id, Provider::released())->errors + )->toHaveKey('provider'); } }); -it('validates every provider scope field against its strict pattern', function (string $provider, string $field, string $good, string $bad) { +it('validates every provider scope field against its strict pattern', function ( + string $provider, + string $field, + string $good, + string $bad +) { $offered = Provider::cases(); $fields = []; foreach (Provider::from($provider)->scopeFields() as $name => $rule) { - $fields['scope_' . $name] = ['account_id' => '123456789012', 'regions' => $provider === 'aws' ? 'us-east-1,eu-west-2' : 'eastus', 'project' => 'my-project-1', 'tenant' => '0f8fad5b-d9cb-469f-a165-70867728950e', 'subscription' => '7c9e6679-7425-40de-944b-e07fc1f90ae7'][$name]; + $fields['scope_' . $name] = [ + 'account_id' => '123456789012', + 'regions' => $provider === 'aws' ? 'us-east-1,eu-west-2' : 'eastus', + 'project' => 'my-project-1', + 'tenant' => '0f8fad5b-d9cb-469f-a165-70867728950e', + 'subscription' => '7c9e6679-7425-40de-944b-e07fc1f90ae7' + ][$name]; } $good_input = cloud_account_input(['provider' => $provider, 'scope_' . $field => $good] + $fields); @@ -89,7 +110,9 @@ function cloud_account_input(array $override = []): array { expect(AccountInput::parse($good_input, 0, $offered)->errors)->toBe([]) ->and(AccountInput::parse($bad_input, 0, $offered)->errors)->toHaveKey('scope_' . $field) - ->and(AccountInput::parse($bad_input, 0, $offered)->errors['scope_' . $field])->toStartWith(AccountInput::scopeLabel($field) . ':'); + ->and( + AccountInput::parse($bad_input, 0, $offered)->errors['scope_' . $field] + )->toStartWith(AccountInput::scopeLabel($field) . ':'); })->with([ ['aws', 'account_id', '123456789012', '12345678901/'], ['aws', 'regions', 'us-east-1, us-gov-west-1', 'us-east-1,evil.example.com'], @@ -144,7 +167,12 @@ function cloud_account_input(array $override = []): array { ]); it('drops stored scope values that no longer match their pattern', function () { - $account = Account::fromRow(['id' => 1, 'provider' => 'aws', 'credential_source' => 'vault', 'scope' => json_encode(['account_id' => '123456789012', 'regions' => 'us-east-1/../x', 'extra' => 'y'])]); + $account = Account::fromRow([ + 'id' => 1, + 'provider' => 'aws', + 'credential_source' => 'vault', + 'scope' => json_encode(['account_id' => '123456789012', 'regions' => 'us-east-1/../x', 'extra' => 'y']) + ]); expect($account?->scope)->toBe(['account_id' => '123456789012']); }); @@ -158,7 +186,11 @@ function cloud_account_input(array $override = []): array { it('names only the changed columns for the audit log', function () { $before = AccountInput::parse(cloud_account_input(), 4, Provider::released())->account; - $after = AccountInput::parse(cloud_account_input(['name' => 'Renamed', 'collect_interval' => '600']), 4, Provider::released())->account; + $after = AccountInput::parse( + cloud_account_input(['name' => 'Renamed', 'collect_interval' => '600']), + 4, + Provider::released() + )->account; expect($after->changedFields($before))->toBe(['name', 'collect_interval']) ->and($before->changedFields(null))->toBe(array_keys($before->toRow())); @@ -179,11 +211,22 @@ function cloud_account_input(array $override = []): array { function cloud_delete_with(array $inTransaction): array { $GLOBALS['__cloud_db_exec'] = []; - $GLOBALS['__cloud_db_rows'] = ['FROM plugin_cloud_account WHERE id' => [['id' => 7, 'provider' => 'digitalocean', 'name' => 'Ops', 'credential_source' => 'vault']]]; + $GLOBALS['__cloud_db_rows'] = [ + 'FROM plugin_cloud_account WHERE id' => [ + ['id' => 7, 'provider' => 'digitalocean', 'name' => 'Ops', 'credential_source' => 'vault'] + ] + ]; $GLOBALS['__cloud_in_tx'] = $inTransaction; - $deleted = (new \Somethingwithproof\Cloud\AccountRepository(false, new \Somethingwithproof\Cloud\FixedClock(1)))->delete(7, 1); - $log = array_map(fn (array $e) => preg_match('/^(BEGIN|COMMIT|ROLLBACK)$/', $e['sql']) ? $e['sql'] : (preg_match('/(?:DELETE \w* ?FROM|INSERT INTO) (plugin_cloud_\w+)/', $e['sql'], $m) ? $m[1] : $e['sql']), $GLOBALS['__cloud_db_exec']); + $deleted = ( + new \Somethingwithproof\Cloud\AccountRepository(false, new \Somethingwithproof\Cloud\FixedClock(1)) + )->delete(7, 1); + $log = array_map( + fn (array $e) => preg_match('/^(BEGIN|COMMIT|ROLLBACK)$/', $e['sql']) ? $e['sql'] : ( + preg_match('/(?:DELETE \w* ?FROM|INSERT INTO) (plugin_cloud_\w+)/', $e['sql'], $m) ? $m[1] : $e['sql'] + ), + $GLOBALS['__cloud_db_exec'] + ); $GLOBALS['__cloud_db_rows'] = []; $GLOBALS['__cloud_in_tx'] = []; @@ -195,7 +238,18 @@ function cloud_delete_with(array $inTransaction): array { [$deleted, $log] = cloud_delete_with([]); expect($deleted)->toBeTrue() - ->and($log)->toBe(['BEGIN', 'plugin_cloud_secret', 'plugin_cloud_series', 'plugin_cloud_lease', 'plugin_cloud_health', 'plugin_cloud_observation', 'plugin_cloud_resource', 'plugin_cloud_account', 'COMMIT', 'plugin_cloud_audit']); + ->and($log)->toBe([ + 'BEGIN', + 'plugin_cloud_secret', + 'plugin_cloud_series', + 'plugin_cloud_lease', + 'plugin_cloud_health', + 'plugin_cloud_observation', + 'plugin_cloud_resource', + 'plugin_cloud_account', + 'COMMIT', + 'plugin_cloud_audit' + ]); }); it('reruns the whole delete when InnoDB ends the transaction partway', function () { @@ -204,7 +258,18 @@ function cloud_delete_with(array $inTransaction): array { expect($deleted)->toBeTrue() ->and(array_slice($log, 0, 4))->toBe(['BEGIN', 'plugin_cloud_secret', 'plugin_cloud_series', 'plugin_cloud_lease']) - ->and(array_slice($log, 4))->toBe(['BEGIN', 'plugin_cloud_secret', 'plugin_cloud_series', 'plugin_cloud_lease', 'plugin_cloud_health', 'plugin_cloud_observation', 'plugin_cloud_resource', 'plugin_cloud_account', 'COMMIT', 'plugin_cloud_audit']); + ->and(array_slice($log, 4))->toBe([ + 'BEGIN', + 'plugin_cloud_secret', + 'plugin_cloud_series', + 'plugin_cloud_lease', + 'plugin_cloud_health', + 'plugin_cloud_observation', + 'plugin_cloud_resource', + 'plugin_cloud_account', + 'COMMIT', + 'plugin_cloud_audit' + ]); }); it('gives up without auditing when every attempt loses its transaction', function () { diff --git a/tests/Unit/DriverContractTest.php b/tests/Unit/DriverContractTest.php index bf328cc..fbd76ee 100644 --- a/tests/Unit/DriverContractTest.php +++ b/tests/Unit/DriverContractTest.php @@ -63,7 +63,9 @@ public function operations(): array { public function verify(Account $account, Secret $credential): VerifyStatus { try { - $status = $this->http->send(new HttpRequest('GET', 'https://api.example.com/v2/account', ['Authorization' => 'Bearer ' . $credential->reveal()]))->status; + $status = $this->http->send( + new HttpRequest('GET', 'https://api.example.com/v2/account', ['Authorization' => 'Bearer ' . $credential->reveal()]) + )->status; } catch (TransportError $e) { throw DriverError::fromTransport($e); } @@ -118,12 +120,23 @@ function cloud_verify_with(?int $status, string $source = 'file'): VerifyStatus file_put_contents($dir . '/token', 'dop_v1_' . str_repeat('a', 64)); chmod($dir . '/token', 0600); - $account = Account::fromRow(['id' => 9, 'provider' => 'digitalocean', 'name' => 'T', 'credential_source' => $source, 'credential_file' => $dir . '/token', 'admin_state' => 'enabled']); + $account = Account::fromRow([ + 'id' => 9, + 'provider' => 'digitalocean', + 'name' => 'T', + 'credential_source' => $source, + 'credential_file' => $dir . '/token', + 'admin_state' => 'enabled' + ]); $drivers = new Drivers(cloud_canned($status)); $drivers->register(Provider::DigitalOcean, static fn (HttpTransport $http): ProviderDriver => new FakeDriver($http)); $clock = new FixedClock(1_800_000_000); - $verifier = new Verifier($drivers, new CredentialStore(new SecretRepository(false, $clock), $dir . '/missing.key'), new AccountRepository(false, $clock)); + $verifier = new Verifier( + $drivers, + new CredentialStore(new SecretRepository(false, $clock), $dir . '/missing.key'), + new AccountRepository(false, $clock) + ); $result = $verifier->verify($account, 1); unlink($dir . '/token'); @@ -136,7 +149,10 @@ function cloud_verify_with(?int $status, string $source = 'file'): VerifyStatus $GLOBALS['__cloud_db_exec'] = []; }); -it('records a fixed status for valid, expired, under-scoped, and unreachable credentials', function (?int $status, VerifyStatus $expected) { +it('records a fixed status for valid, expired, under-scoped, and unreachable credentials', function ( + ?int $status, + VerifyStatus $expected +) { expect(cloud_verify_with($status))->toBe($expected); $update = $GLOBALS['__cloud_db_exec'][0]; @@ -157,7 +173,11 @@ function cloud_verify_with(?int $status, string $source = 'file'): VerifyStatus it('reports a configuration status for a provider without a driver', function () { $account = Account::fromRow(['id' => 9, 'provider' => 'digitalocean', 'credential_source' => 'vault']); $clock = new FixedClock(1); - $verifier = new Verifier(new Drivers(cloud_canned(200)), new CredentialStore(new SecretRepository(false, $clock), '/nonexistent'), new AccountRepository(false, $clock)); + $verifier = new Verifier( + new Drivers(cloud_canned(200)), + new CredentialStore(new SecretRepository(false, $clock), '/nonexistent'), + new AccountRepository(false, $clock) + ); expect($verifier->verify($account, 1))->toBe(VerifyStatus::Config); }); @@ -166,9 +186,16 @@ function cloud_verify_with(?int $status, string $source = 'file'): VerifyStatus $GLOBALS['__cloud_log'] = []; $account = Account::fromRow(['id' => 9, 'provider' => 'digitalocean', 'credential_source' => 'vault']); $drivers = new Drivers(cloud_canned(200)); - $drivers->register(Provider::DigitalOcean, static fn (HttpTransport $http): ProviderDriver => throw new RuntimeException('provider said sk-live-123')); + $drivers->register( + Provider::DigitalOcean, + static fn (HttpTransport $http): ProviderDriver => throw new RuntimeException('provider said sk-live-123') + ); $clock = new FixedClock(1); - $verifier = new Verifier($drivers, new CredentialStore(new SecretRepository(false, $clock), '/nonexistent'), new AccountRepository(false, $clock)); + $verifier = new Verifier( + $drivers, + new CredentialStore(new SecretRepository(false, $clock), '/nonexistent'), + new AccountRepository(false, $clock) + ); expect($verifier->verify($account, 1))->toBe(VerifyStatus::Config) ->and(implode("\n", array_column($GLOBALS['__cloud_log'], 'message')))->not->toContain('sk-live-123'); @@ -179,8 +206,12 @@ function cloud_verify_with(?int $status, string $source = 'file'): VerifyStatus expect(mb_strlen($long->name))->toBe(255) ->and(mb_strlen($long->region))->toBe(64) - ->and(fn () => new \Somethingwithproof\Cloud\CloudResource('droplet', str_repeat('i', 256), 'x'))->toThrow(DriverError::class) - ->and(fn () => new \Somethingwithproof\Cloud\CloudResource(str_repeat('t', 65), 'd1', 'x'))->toThrow(DriverError::class) + ->and( + fn () => new \Somethingwithproof\Cloud\CloudResource('droplet', str_repeat('i', 256), 'x') + )->toThrow(DriverError::class) + ->and( + fn () => new \Somethingwithproof\Cloud\CloudResource(str_repeat('t', 65), 'd1', 'x') + )->toThrow(DriverError::class) ->and(fn () => new \Somethingwithproof\Cloud\CloudResource('droplet', "d1\nd2", 'x'))->toThrow(DriverError::class) ->and(fn () => new \Somethingwithproof\Cloud\CloudResource('droplet', '', 'x'))->toThrow(DriverError::class); }); @@ -200,7 +231,9 @@ function cloud_verify_with(?int $status, string $source = 'file'): VerifyStatus $drivers = Drivers::production(); foreach (Provider::cases() as $provider) { - $driver = $drivers->for(Account::fromRow(['id' => 1, 'provider' => $provider->value, 'credential_source' => 'vault'])); + $driver = $drivers->for( + Account::fromRow(['id' => 1, 'provider' => $provider->value, 'credential_source' => 'vault']) + ); foreach ($driver?->operations() ?? [] as $operation) { expect($operation->method === 'GET' || $operation->bodyPattern !== null)->toBeTrue($operation->name); @@ -211,7 +244,16 @@ function cloud_verify_with(?int $status, string $source = 'file'): VerifyStatus }); it('maps every transport failure to an error class', function () { - foreach (['url_rejected', 'host_refused', 'operation_refused', 'tls_verify', 'malformed', 'too_large', 'total_timeout', 'connect_refused'] as $kind) { + foreach ([ + 'url_rejected', + 'host_refused', + 'operation_refused', + 'tls_verify', + 'malformed', + 'too_large', + 'total_timeout', + 'connect_refused' + ] as $kind) { expect((new TransportError($kind))->errorClass())->toBeInstanceOf(ErrorClass::class); } diff --git a/tests/Unit/FreshnessTest.php b/tests/Unit/FreshnessTest.php index 9027324..d558154 100644 --- a/tests/Unit/FreshnessTest.php +++ b/tests/Unit/FreshnessTest.php @@ -22,7 +22,10 @@ use Somethingwithproof\Cloud\FreshnessEvaluator; use Somethingwithproof\Cloud\Observation; -it('classifies datapoints by their provider time against period, delay, and interval', function (int $age, Freshness $expected) { +it('classifies datapoints by their provider time against period, delay, and interval', function ( + int $age, + Freshness $expected +) { $now = 1_800_000_000; $fresh = new FreshnessEvaluator(new FixedClock($now)); @@ -41,7 +44,14 @@ it('never counts the fetch time as a measurement', function () { $now = 1_800_000_000; - expect((new FreshnessEvaluator(new FixedClock($now)))->evaluate(new Observation(1, 'cpu', 1.0, $now - 86400, $now), 60, 0, 300))->toBe(Freshness::Stale); + expect( + (new FreshnessEvaluator(new FixedClock($now)))->evaluate( + new Observation(1, 'cpu', 1.0, $now - 86400, $now), + 60, + 0, + 300 + ) + )->toBe(Freshness::Stale); }); it('reports never-observed series as never, and only current or delayed as usable', function () { @@ -53,16 +63,33 @@ }); it('pins observation rows with NULL, empty, and malformed values', function () { - expect(Observation::fromRow(['resource_id' => '3', 'metric' => 'cpu', 'value' => null, 'observed_at' => '', 'fetched_at' => 'x'])) + expect( + Observation::fromRow([ + 'resource_id' => '3', + 'metric' => 'cpu', + 'value' => null, + 'observed_at' => '', + 'fetched_at' => 'x' + ]) + ) ->toEqual(new Observation(3, 'cpu', null, 0, 0)) - ->and(Observation::fromRow(['resource_id' => '3', 'metric' => 'cpu', 'value' => 'U']))->toEqual(new Observation(3, 'cpu', null, 0, 0)) - ->and(Observation::fromRow(['resource_id' => '3', 'metric' => 'cpu', 'value' => '0']))->toEqual(new Observation(3, 'cpu', 0.0, 0, 0)) + ->and( + Observation::fromRow(['resource_id' => '3', 'metric' => 'cpu', 'value' => 'U']) + )->toEqual(new Observation(3, 'cpu', null, 0, 0)) + ->and( + Observation::fromRow(['resource_id' => '3', 'metric' => 'cpu', 'value' => '0']) + )->toEqual(new Observation(3, 'cpu', 0.0, 0, 0)) ->and(Observation::fromRow(['resource_id' => '0', 'metric' => 'cpu']))->toBeNull() ->and(Observation::fromRow(['resource_id' => '3', 'metric' => '']))->toBeNull(); }); it('pins health rows with unknown states', function () { - $health = \Somethingwithproof\Cloud\AccountHealth::fromRow(['account_id' => '2', 'collection' => 'weird', 'error_class' => 'nope', 'run_duration' => '-1']); + $health = \Somethingwithproof\Cloud\AccountHealth::fromRow([ + 'account_id' => '2', + 'collection' => 'weird', + 'error_class' => 'nope', + 'run_duration' => '-1' + ]); expect($health->collection)->toBe(\Somethingwithproof\Cloud\CollectionState::Never) ->and($health->error)->toBeNull() diff --git a/tests/Unit/HealthWarningsTest.php b/tests/Unit/HealthWarningsTest.php index cba8540..7809f6f 100644 --- a/tests/Unit/HealthWarningsTest.php +++ b/tests/Unit/HealthWarningsTest.php @@ -46,7 +46,16 @@ }); function cloud_warn_account(array $row = []): Account { - return Account::fromRow($row + ['id' => 4, 'provider' => 'digitalocean', 'name' => 'Ops', 'credential_source' => 'vault', 'collect_interval' => 300, 'admin_state' => 'enabled']); + return Account::fromRow( + $row + [ + 'id' => 4, + 'provider' => 'digitalocean', + 'name' => 'Ops', + 'credential_source' => 'vault', + 'collect_interval' => 300, + 'admin_state' => 'enabled' + ] + ); } function cloud_warnings(string $key, array $accounts, int $poller = 300): array { @@ -54,7 +63,20 @@ function cloud_warnings(string $key, array $accounts, int $poller = 300): array } it('has no warnings for a usable key, safe files, and matching intervals', function () { - expect(cloud_warnings($this->key, [cloud_warn_account(), cloud_warn_account(['id' => 5, 'credential_source' => 'file', 'credential_file' => $this->token, 'collect_interval' => 600])]))->toBe([]); + expect( + cloud_warnings( + $this->key, + [ + cloud_warn_account(), + cloud_warn_account([ + 'id' => 5, + 'credential_source' => 'file', + 'credential_file' => $this->token, + 'collect_interval' => 600 + ]) + ] + ) + )->toBe([]); }); it('warns everyone when the vault key file is missing or refused', function (string $fixture, string $reason) { @@ -99,7 +121,10 @@ function cloud_warnings(string $key, array $accounts, int $poller = 300): array })->call($this), }; - $warnings = cloud_warnings($this->key, [cloud_warn_account(['credential_source' => 'file', 'credential_file' => $path])]); + $warnings = cloud_warnings( + $this->key, + [cloud_warn_account(['credential_source' => 'file', 'credential_file' => $path])] + ); expect($warnings)->toHaveCount(1) ->and($warnings[0]['admin'])->toBeTrue() @@ -112,10 +137,19 @@ function cloud_warnings(string $key, array $accounts, int $poller = 300): array ['link', 'symbolic link'], ]); -it('warns when the poller interval cannot honour the collection interval', function (int $collect, int $poller, ?string $expected) { - $messages = array_column(cloud_warnings($this->key, [cloud_warn_account(['collect_interval' => $collect])], $poller), 'message'); - - expect($messages)->toBe($expected === null ? [] : ['Ops: the collection interval of ' . $collect . ' seconds ' . $expected]); +it('warns when the poller interval cannot honour the collection interval', function ( + int $collect, + int $poller, + ?string $expected +) { + $messages = array_column( + cloud_warnings($this->key, [cloud_warn_account(['collect_interval' => $collect])], $poller), + 'message' + ); + + expect($messages)->toBe( + $expected === null ? [] : ['Ops: the collection interval of ' . $collect . ' seconds ' . $expected] + ); })->with([ [300, 300, null], [600, 300, null], @@ -127,5 +161,17 @@ function cloud_warnings(string $key, array $accounts, int $poller = 300): array ]); it('skips disabled accounts', function () { - expect(cloud_warnings($this->key, [cloud_warn_account(['admin_state' => 'disabled', 'credential_source' => 'file', 'credential_file' => '/none', 'collect_interval' => 450])]))->toBe([]); + expect( + cloud_warnings( + $this->key, + [ + cloud_warn_account([ + 'admin_state' => 'disabled', + 'credential_source' => 'file', + 'credential_file' => '/none', + 'collect_interval' => 450 + ]) + ] + ) + )->toBe([]); }); diff --git a/tests/Unit/VaultTest.php b/tests/Unit/VaultTest.php index 367bbda..723e083 100644 --- a/tests/Unit/VaultTest.php +++ b/tests/Unit/VaultTest.php @@ -95,7 +95,9 @@ function cloud_refusal(callable $read): string { it('reports a replaced key as such, not as corruption', function () { $entry = (new Vault(VaultKey::fromBytes(random_bytes(32))))->encrypt(new Secret(CLOUD_TEST_SECRET), 5, 'credential'); - expect(cloud_refusal(fn () => (new Vault(VaultKey::fromBytes(random_bytes(32))))->decrypt($entry, 5, 'credential')))->toContain('different vault key'); + expect( + cloud_refusal(fn () => (new Vault(VaultKey::fromBytes(random_bytes(32))))->decrypt($entry, 5, 'credential')) + )->toContain('different vault key'); }); it('reads a key file of 32 raw bytes or 64 hex characters', function () { @@ -152,9 +154,13 @@ function cloud_refusal(callable $read): string { ->and(cloud_refusal(fn () => CredentialFile::read('token')))->toContain('absolute path') ->and(cloud_refusal(fn () => CredentialFile::read($dir . '/link')))->toContain('symbolic link') ->and(cloud_refusal(fn () => CredentialFile::read($dir)))->toContain('not a regular file') - ->and(cloud_refusal(fn () => CredentialFile::read(cloud_file($dir, 'open', CLOUD_TEST_SECRET, 0644))))->toContain('other users') + ->and( + cloud_refusal(fn () => CredentialFile::read(cloud_file($dir, 'open', CLOUD_TEST_SECRET, 0644))) + )->toContain('other users') ->and(cloud_refusal(fn () => CredentialFile::read(cloud_file($dir, 'empty', "\n"))))->toContain('empty') - ->and(cloud_refusal(fn () => CredentialFile::read(cloud_file($dir, 'big', str_repeat('a', CredentialFile::MAX_BYTES + 1)))))->toContain('larger than allowed'); + ->and( + cloud_refusal(fn () => CredentialFile::read(cloud_file($dir, 'big', str_repeat('a', CredentialFile::MAX_BYTES + 1)))) + )->toContain('larger than allowed'); }); it('never puts secret material in a refusal message', function () { @@ -211,7 +217,18 @@ function cloud_refusal(callable $read): string { $clean = $redactor->clean($text); - foreach (['p@ss/word+with spaces', rawurlencode('p@ss/word+with spaces'), urlencode('p@ss/word+with spaces'), CLOUD_TEST_SECRET, 'abc123', 'eyJhbGciOi', 'deadbeef', 'AKID%2F2026', 'ya29.a0Af', 'MIIEv'] as $leak) { + foreach ([ + 'p@ss/word+with spaces', + rawurlencode('p@ss/word+with spaces'), + urlencode('p@ss/word+with spaces'), + CLOUD_TEST_SECRET, + 'abc123', + 'eyJhbGciOi', + 'deadbeef', + 'AKID%2F2026', + 'ya29.a0Af', + 'MIIEv' + ] as $leak) { expect($clean)->not->toContain($leak); } @@ -260,7 +277,9 @@ function cloud_refusal(callable $read): string { it('refuses a FIFO before opening it, which would block', function () { $fifo = $this->dir . '/fifo'; - $made = function_exists('posix_mkfifo') ? posix_mkfifo($fifo, 0600) : (exec('mkfifo -m 600 ' . escapeshellarg($fifo) . ' 2>/dev/null', $out, $rc) !== false && $rc === 0); + $made = function_exists('posix_mkfifo') ? posix_mkfifo($fifo, 0600) : ( + exec('mkfifo -m 600 ' . escapeshellarg($fifo) . ' 2>/dev/null', $out, $rc) !== false && $rc === 0 + ); if (!$made) { $this->markTestSkipped('posix_mkfifo is not available'); @@ -274,10 +293,20 @@ function cloud_refusal(callable $read): string { }); it('pins vault rows with missing, wrongly sized, and malformed fields', function () { - $row = ['nonce' => str_repeat('n', 12), 'ciphertext' => 'c', 'tag' => str_repeat('t', 16), 'key_id' => 'k1', 'expires_at' => '1800000000']; - - expect(VaultEntry::fromRow($row))->toEqual(new VaultEntry(str_repeat('n', 12), 'c', str_repeat('t', 16), 'k1', 1800000000)) - ->and(VaultEntry::fromRow(['expires_at' => 'x', 'key_id' => null] + $row))->toEqual(new VaultEntry(str_repeat('n', 12), 'c', str_repeat('t', 16), '', 0)) + $row = [ + 'nonce' => str_repeat('n', 12), + 'ciphertext' => 'c', + 'tag' => str_repeat('t', 16), + 'key_id' => 'k1', + 'expires_at' => '1800000000' + ]; + + expect(VaultEntry::fromRow($row))->toEqual( + new VaultEntry(str_repeat('n', 12), 'c', str_repeat('t', 16), 'k1', 1800000000) + ) + ->and(VaultEntry::fromRow(['expires_at' => 'x', 'key_id' => null] + $row))->toEqual( + new VaultEntry(str_repeat('n', 12), 'c', str_repeat('t', 16), '', 0) + ) ->and(VaultEntry::fromRow(['nonce' => str_repeat('n', 11)] + $row))->toBeNull() ->and(VaultEntry::fromRow(['tag' => str_repeat('t', 15)] + $row))->toBeNull() ->and(VaultEntry::fromRow(['ciphertext' => null] + $row))->toBeNull() diff --git a/tests/bin/collector-flow.php b/tests/bin/collector-flow.php index 5df1be6..50d49eb 100644 --- a/tests/bin/collector-flow.php +++ b/tests/bin/collector-flow.php @@ -87,7 +87,10 @@ public function discover(Account $account, Secret $credential): Inventory { self::$order[] = $account->name; self::$clock?->advance(self::$tick); - return new Inventory(array_map(fn (string $id) => new CloudResource('droplet', $id, 'Droplet ' . $id, 'nyc3'), self::$present), 1); + return new Inventory( + array_map(fn (string $id) => new CloudResource('droplet', $id, 'Droplet ' . $id, 'nyc3'), self::$present), + 1 + ); } public function collect(Account $account, Secret $credential, array $requests): CollectResult { @@ -95,7 +98,13 @@ public function collect(Account $account, Secret $credential, array $requests): foreach ($requests as $request) { self::$collected[] = $request->providerId . '/' . $request->metric; - $out[] = new Observation($request->resourceId, $request->metric, 42.5, self::$observedAt, self::$observedAt + 30); + $out[] = new Observation( + $request->resourceId, + $request->metric, + 42.5, + self::$observedAt, + self::$observedAt + 30 + ); } return new CollectResult($out, count($requests)); @@ -116,13 +125,19 @@ public function estimate(array $requests, int $intervalSeconds): UsageEstimate { function flow_account($name, $poller, $state) { global $flow_dir; - db_execute_prepared("INSERT INTO plugin_cloud_account (provider, name, poller_id, credential_source, credential_file, collect_interval, discover_interval, admin_state) VALUES ('digitalocean', ?, ?, 'file', ?, 300, 3600, ?)", array($name, $poller, $flow_dir . '/token', $state)); + db_execute_prepared( + "INSERT INTO plugin_cloud_account (provider, name, poller_id, credential_source, credential_file, " . + "collect_interval, discover_interval, admin_state) VALUES ('digitalocean', ?, ?, 'file', ?, 300, 3600, ?)", + array($name, $poller, $flow_dir . '/token', $state) + ); return (int) db_fetch_insert_id(); } function flow_collector($clock, $holder) { - $drivers = new Drivers(static fn (OutboundPolicy $p): HttpTransport => new \Somethingwithproof\Cloud\RefusingTransport()); + $drivers = new Drivers( + static fn (OutboundPolicy $p): HttpTransport => new \Somethingwithproof\Cloud\RefusingTransport() + ); $drivers->register(Provider::DigitalOcean, static fn (HttpTransport $http): ProviderDriver => new FlowDriver($http)); return new Collector( @@ -142,15 +157,34 @@ function flow_collector($clock, $holder) { FlowDriver::$observedAt = 1800000000 - 120; $result['run1'] = flow_collector($flow_clock, 'h1')->run(1, 240); $result['discoveries'] = FlowDriver::$discoveries; -$result['resources'] = (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_cloud_resource WHERE account_id = ?', array($main)); -$result['others'] = (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_cloud_resource WHERE account_id IN (?, ?)', array($remote, $disabled)); +$result['resources'] = (int) db_fetch_cell_prepared( + 'SELECT COUNT(*) FROM plugin_cloud_resource WHERE account_id = ?', + array($main) +); +$result['others'] = (int) db_fetch_cell_prepared( + 'SELECT COUNT(*) FROM plugin_cloud_resource WHERE account_id IN (?, ?)', + array($remote, $disabled) +); // Map d1/cpu to an active data source, d2/cpu to an inactive one, and // d1/load to a data source that does not exist. -$d1 = (int) db_fetch_cell_prepared("SELECT id FROM plugin_cloud_resource WHERE account_id = ? AND provider_id = 'd1'", array($main)); -$d2 = (int) db_fetch_cell_prepared("SELECT id FROM plugin_cloud_resource WHERE account_id = ? AND provider_id = 'd2'", array($main)); -db_execute("INSERT INTO data_template_data (local_data_id, data_template_id, name, active) VALUES (900001, 0, 'flow on', 'on'), (900002, 0, 'flow off', '')"); -db_execute_prepared('INSERT INTO plugin_cloud_series (local_data_id, account_id, resource_id, metric) VALUES (900001, ?, ?, ?), (900002, ?, ?, ?), (900003, ?, ?, ?)', array($main, $d1, 'cpu', $main, $d2, 'cpu', $main, $d1, 'load')); +$d1 = (int) db_fetch_cell_prepared( + "SELECT id FROM plugin_cloud_resource WHERE account_id = ? AND provider_id = 'd1'", + array($main) +); +$d2 = (int) db_fetch_cell_prepared( + "SELECT id FROM plugin_cloud_resource WHERE account_id = ? AND provider_id = 'd2'", + array($main) +); +db_execute( + "INSERT INTO data_template_data (local_data_id, data_template_id, name, active) VALUES (900001, 0, 'flow on', " . + "'on'), (900002, 0, 'flow off', '')" +); +db_execute_prepared( + 'INSERT INTO plugin_cloud_series (local_data_id, account_id, resource_id, metric) VALUES (900001, ?, ?, ?), ' . + '(900002, ?, ?, ?), (900003, ?, ?, ?)', + array($main, $d1, 'cpu', $main, $d2, 'cpu', $main, $d1, 'load') +); // Run 2 within the interval does nothing; run 3 after it collects. $flow_clock->advance(60); @@ -171,15 +205,29 @@ function flow_collector($clock, $holder) { flow_collector($flow_clock, 'h3b')->run(1, 240); $result['collected_at_296'] = count(FlowDriver::$collected); $result['discoveries_after'] = FlowDriver::$discoveries; -$result['observation'] = db_fetch_row_prepared('SELECT value, observed_at, status FROM plugin_cloud_observation WHERE resource_id = ? AND metric = ?', array($d1, 'cpu')); -$result['health'] = db_fetch_row_prepared('SELECT collection, series_total, series_read FROM plugin_cloud_health WHERE account_id = ?', array($main)); +$result['observation'] = db_fetch_row_prepared( + 'SELECT value, observed_at, status FROM plugin_cloud_observation WHERE resource_id = ? AND metric = ?', + array($d1, 'cpu') +); +$result['health'] = db_fetch_row_prepared( + 'SELECT collection, series_total, series_read FROM plugin_cloud_health WHERE account_id = ?', + array($main) +); // A writer without the lease, and an older datapoint, change nothing. $observations = new ObservationRepository(false); -$observations->write($main, 'stranger', $flow_clock->now(), new Observation($d1, 'cpu', 1.0, $flow_clock->now(), $flow_clock->now())); +$observations->write( + $main, + 'stranger', + $flow_clock->now(), + new Observation($d1, 'cpu', 1.0, $flow_clock->now(), $flow_clock->now()) +); (new LeaseRepository(false, $flow_clock))->acquire($main, 'h4', 3600); $observations->write($main, 'h4', $flow_clock->now(), new Observation($d1, 'cpu', 2.0, 1, $flow_clock->now())); -$result['after_foreign_writes'] = db_fetch_row_prepared('SELECT value, observed_at FROM plugin_cloud_observation WHERE resource_id = ? AND metric = ?', array($d1, 'cpu')); +$result['after_foreign_writes'] = db_fetch_row_prepared( + 'SELECT value, observed_at FROM plugin_cloud_observation WHERE resource_id = ? AND metric = ?', + array($d1, 'cpu') +); // A lease held by another live run makes this run skip the account. $flow_clock->advance(400); @@ -194,13 +242,23 @@ function flow_collector($clock, $holder) { for ($i = 0; $i < 3; $i++) { $flow_clock->advance(3700); flow_collector($flow_clock, 'h7')->run(1, 240); - $result['d2_lifecycle'][] = db_fetch_cell_prepared('SELECT lifecycle FROM plugin_cloud_resource WHERE id = ?', array($d2)); + $result['d2_lifecycle'][] = db_fetch_cell_prepared( + 'SELECT lifecycle FROM plugin_cloud_resource WHERE id = ?', + array($d2) + ); } // A writer without the lease cannot replace health either. $health_before = db_fetch_row_prepared('SELECT * FROM plugin_cloud_health WHERE account_id = ?', array($main)); -(new HealthRepository(false))->save(new \Somethingwithproof\Cloud\AccountHealth($main, 1, 1, 0.0, \Somethingwithproof\Cloud\CollectionState::Failed), 'stranger', $flow_clock->now()); -$result['health_unchanged'] = db_fetch_row_prepared('SELECT * FROM plugin_cloud_health WHERE account_id = ?', array($main)) == $health_before; +(new HealthRepository(false))->save( + new \Somethingwithproof\Cloud\AccountHealth($main, 1, 1, 0.0, \Somethingwithproof\Cloud\CollectionState::Failed), + 'stranger', + $flow_clock->now() +); +$result['health_unchanged'] = db_fetch_row_prepared( + 'SELECT * FROM plugin_cloud_health WHERE account_id = ?', + array($main) +) == $health_before; // Each discovery takes 300 s against a 100 s budget, so a run reaches one // account. The never-run account goes first, then the least recent. diff --git a/tests/bin/collector-restart.php b/tests/bin/collector-restart.php index 4cb3e4f..5db4ad0 100644 --- a/tests/bin/collector-restart.php +++ b/tests/bin/collector-restart.php @@ -108,8 +108,13 @@ public function estimate(array $requests, int $intervalSeconds): UsageEstimate { } function restart_collector(FixedClock $clock, string $holder): Collector { - $drivers = new Drivers(static fn (OutboundPolicy $p): HttpTransport => new \Somethingwithproof\Cloud\RefusingTransport()); - $drivers->register(Provider::DigitalOcean, static fn (HttpTransport $http): ProviderDriver => new RestartDriver($http)); + $drivers = new Drivers( + static fn (OutboundPolicy $p): HttpTransport => new \Somethingwithproof\Cloud\RefusingTransport() + ); + $drivers->register( + Provider::DigitalOcean, + static fn (HttpTransport $http): ProviderDriver => new RestartDriver($http) + ); return new Collector( new \Somethingwithproof\Cloud\AccountRepository(false, $clock), $drivers, @@ -121,9 +126,17 @@ function restart_collector(FixedClock $clock, string $holder): Collector { function restart_state(int $account): array { return array( - 'lease' => db_fetch_row_prepared('SELECT holder, expires_at FROM plugin_cloud_lease WHERE account_id = ?', array($account)), - 'health' => db_fetch_row_prepared('SELECT run_started, collection, series_read FROM plugin_cloud_health WHERE account_id = ?', array($account)), - 'observations' => db_fetch_assoc('SELECT metric, value, observed_at, status FROM plugin_cloud_observation ORDER BY metric'), + 'lease' => db_fetch_row_prepared( + 'SELECT holder, expires_at FROM plugin_cloud_lease WHERE account_id = ?', + array($account) + ), + 'health' => db_fetch_row_prepared( + 'SELECT run_started, collection, series_read FROM plugin_cloud_health WHERE account_id = ?', + array($account) + ), + 'observations' => db_fetch_assoc( + 'SELECT metric, value, observed_at, status FROM plugin_cloud_observation ORDER BY metric' + ), ); } @@ -132,13 +145,24 @@ function restart_state(int $account): array { switch ($action) { case 'collector_second': // An enabled account a running collector would lease at once. - db_execute("INSERT INTO plugin_cloud_account (provider, name, poller_id, credential_source, admin_state) VALUES ('digitalocean', 'Second start', 1, 'vault', 'enabled')"); + db_execute( + "INSERT INTO plugin_cloud_account (provider, name, poller_id, credential_source, admin_state) VALUES " . + "('digitalocean', 'Second start', 1, 'vault', 'enabled')" + ); // A live process holds the collector slot for poller 1. Cacti 1.2.x // treats a slot as held only when the holder runs the same script, // so the stand-in names poller_cloud.php on its command line. $script = $config['base_path'] . '/plugins/cloud/poller_cloud.php'; - $holder = proc_open(array(PHP_BINARY, '-r', 'sleep(60);', $script), array(0 => array('file', '/dev/null', 'r'), 1 => array('file', '/dev/null', 'w'), 2 => array('file', '/dev/null', 'w')), $pipes); + $holder = proc_open( + array(PHP_BINARY, '-r', 'sleep(60);', $script), + array( + 0 => array('file', '/dev/null', 'r'), + 1 => array('file', '/dev/null', 'w'), + 2 => array('file', '/dev/null', 'w') + ), + $pipes + ); $status = proc_get_status($holder); register_process('cloud', 'collector', 1, $status['pid'], 300); $started = microtime(true); @@ -146,10 +170,20 @@ function restart_state(int $account): array { proc_terminate($holder, 9); proc_close($holder); unregister_process('cloud', 'collector', 1); - $result = array('rc' => $rc, 'seconds' => round(microtime(true) - $started, 1), 'output' => implode("\n", $lines), 'leases' => (int) db_fetch_cell('SELECT COUNT(*) FROM plugin_cloud_lease')); + $result = array( + 'rc' => $rc, + 'seconds' => round(microtime(true) - $started, 1), + 'output' => implode("\n", $lines), + 'leases' => (int) db_fetch_cell('SELECT COUNT(*) FROM plugin_cloud_lease') + ); // Control: with the slot free, the same start does take the lease. - exec(escapeshellarg(PHP_BINARY) . ' -q ' . escapeshellarg($config['base_path'] . '/plugins/cloud/poller_cloud.php') . ' --poller=1 --force 2>&1', $lines, $rc); + exec( + escapeshellarg(PHP_BINARY) . ' -q ' + . escapeshellarg($config['base_path'] . '/plugins/cloud/poller_cloud.php') . ' --poller=1 --force 2>&1', + $lines, + $rc + ); $result['leases_when_free'] = (int) db_fetch_cell('SELECT COUNT(*) FROM plugin_cloud_lease'); break; @@ -161,16 +195,35 @@ function restart_state(int $account): array { case 'collector_kill': file_put_contents($restart_token, 'dop_v1_' . str_repeat('c', 64)); chmod($restart_token, 0600); - db_execute_prepared("INSERT INTO plugin_cloud_account (provider, name, poller_id, credential_source, credential_file, collect_interval, discover_interval, admin_state) VALUES ('digitalocean', 'Restart', 1, 'file', ?, 300, 3600, 'enabled')", array($restart_token)); + db_execute_prepared( + "INSERT INTO plugin_cloud_account (provider, name, poller_id, credential_source, credential_file, " . + "collect_interval, discover_interval, admin_state) VALUES ('digitalocean', 'Restart', 1, 'file', ?, 300, 3600, " . + "'enabled')", + array($restart_token) + ); $account = (int) db_fetch_insert_id(); // Discovery has run once; one active series is mapped. - db_execute_prepared("INSERT INTO plugin_cloud_resource (account_id, type, provider_id, name, region, lifecycle, first_seen, last_seen) VALUES (?, 'droplet', 'r1', 'Restart one', 'nyc3', 'active', ?, ?)", array($account, RESTART_TIME - 600, RESTART_TIME - 600)); + db_execute_prepared( + "INSERT INTO plugin_cloud_resource (account_id, type, provider_id, name, region, lifecycle, first_seen, " . + "last_seen) VALUES (?, 'droplet', 'r1', 'Restart one', 'nyc3', 'active', ?, ?)", + array($account, RESTART_TIME - 600, RESTART_TIME - 600) + ); $resource = (int) db_fetch_insert_id(); - db_execute("INSERT INTO data_template_data (local_data_id, data_template_id, name, active) VALUES (900101, 0, 'restart', 'on')"); - db_execute_prepared("INSERT INTO plugin_cloud_series (local_data_id, account_id, resource_id, metric) VALUES (900101, ?, ?, 'cpu')", array($account, $resource)); - - exec(escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg(__DIR__ . '/lifecycle.php') . ' collector_victim 2>&1', $lines, $rc); + db_execute( + "INSERT INTO data_template_data (local_data_id, data_template_id, name, active) VALUES (900101, 0, 'restart', " . + "'on')" + ); + db_execute_prepared( + "INSERT INTO plugin_cloud_series (local_data_id, account_id, resource_id, metric) VALUES (900101, ?, ?, 'cpu')", + array($account, $resource) + ); + + exec( + escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg(__DIR__ . '/lifecycle.php') . ' collector_victim 2>&1', + $lines, + $rc + ); $result = array('victim_rc' => $rc, 'after_kill' => restart_state($account)); // Inside the dead run's lease, the account is skipped, not doubled. diff --git a/tests/bin/lifecycle.php b/tests/bin/lifecycle.php index dfc25b3..e6296cf 100644 --- a/tests/bin/lifecycle.php +++ b/tests/bin/lifecycle.php @@ -47,7 +47,10 @@ case 'reset': api_plugin_uninstall('cloud'); - foreach (db_fetch_assoc("SELECT TABLE_NAME AS t FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE 'plugin\\_cloud\\_%'") as $row) { + foreach (db_fetch_assoc( + "SELECT TABLE_NAME AS t FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE " . + "'plugin\\_cloud\\_%'" + ) as $row) { db_execute('DROP TABLE `' . $row['t'] . '`'); } @@ -108,7 +111,9 @@ break; case 'seed': // An account row, so table drops and keeps are visible. - db_execute("INSERT INTO plugin_cloud_account (provider, name, credential_source) VALUES ('digitalocean', 'Seed', 'vault')"); + db_execute( + "INSERT INTO plugin_cloud_account (provider, name, credential_source) VALUES ('digitalocean', 'Seed', 'vault')" + ); break; case 'credential_flow': @@ -125,20 +130,45 @@ $clock = new \Somethingwithproof\Cloud\SystemClock(); $accounts = new \Somethingwithproof\Cloud\AccountRepository(false, $clock); - $store = new \Somethingwithproof\Cloud\CredentialStore(new \Somethingwithproof\Cloud\SecretRepository(false, $clock), $keyFile); - $input = array('provider' => 'digitalocean', 'name' => 'Flow', 'poller_id' => '1', 'credential_source' => 'vault', 'collect_interval' => '300', 'discover_interval' => '3600', 'request_share' => '50', 'enabled' => 'on'); - - $id = $accounts->save(\Somethingwithproof\Cloud\AccountInput::parse($input, 0, \Somethingwithproof\Cloud\Provider::released())->account, 1); + $store = new \Somethingwithproof\Cloud\CredentialStore( + new \Somethingwithproof\Cloud\SecretRepository(false, $clock), + $keyFile + ); + $input = array( + 'provider' => 'digitalocean', + 'name' => 'Flow', + 'poller_id' => '1', + 'credential_source' => 'vault', + 'collect_interval' => '300', + 'discover_interval' => '3600', + 'request_share' => '50', + 'enabled' => 'on' + ); + + $id = $accounts->save( + \Somethingwithproof\Cloud\AccountInput::parse($input, 0, \Somethingwithproof\Cloud\Provider::released())->account, + 1 + ); $store->storeVaultCredential($id, new \Somethingwithproof\Cloud\Secret($secret)); $accounts->recordCredentialChange($id, 1); - $accounts->save(\Somethingwithproof\Cloud\AccountInput::parse(array('name' => 'Flow renamed') + $input, $id, \Somethingwithproof\Cloud\Provider::released())->account, 1); + $accounts->save( + \Somethingwithproof\Cloud\AccountInput::parse( + array('name' => 'Flow renamed') + $input, + $id, + \Somethingwithproof\Cloud\Provider::released() + )->account, + 1 + ); $accounts->recordVerify($id, \Somethingwithproof\Cloud\VerifyStatus::Invalid, 1); $readBack = $store->credentialFor($accounts->find($id))->reveal() === $secret; $audit = array_reverse(array_column($accounts->auditLog($id), 'action')); $leaks = array(); - foreach (db_fetch_assoc("SELECT TABLE_NAME AS t FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE 'plugin\\_cloud\\_%'") as $table) { + foreach (db_fetch_assoc( + "SELECT TABLE_NAME AS t FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE " . + "'plugin\\_cloud\\_%'" + ) as $table) { foreach (db_fetch_assoc('SELECT * FROM `' . $table['t'] . '`') as $row) { if (strpos(implode("\0", array_map('strval', $row)), $secret) !== false) { $leaks[] = $table['t']; @@ -153,7 +183,12 @@ $accounts->delete($id, 1); unlink($keyFile); - $result = array('read_back' => $readBack, 'audit' => $audit, 'leaks' => $leaks, 'account_gone' => $accounts->find($id) === null); + $result = array( + 'read_back' => $readBack, + 'audit' => $audit, + 'leaks' => $leaks, + 'account_gone' => $accounts->find($id) === null + ); break; case 'collector_flow': @@ -174,7 +209,10 @@ case 'repair_as_viewer': // A viewer opens a plugin page after the realm rows went missing. db_execute("DELETE FROM user_auth WHERE username = 'cloudviewer'"); - db_execute("INSERT INTO user_auth (username, password, realm, full_name, enabled) VALUES ('cloudviewer', '', 0, 'viewer', 'on')"); + db_execute( + "INSERT INTO user_auth (username, password, realm, full_name, enabled) VALUES ('cloudviewer', '', 0, 'viewer', " . + "'on')" + ); $viewer = (int) db_fetch_insert_id(); db_execute("DELETE FROM plugin_realms WHERE plugin = 'cloud'"); db_execute("DELETE FROM plugin_hooks WHERE name = 'cloud'"); @@ -182,7 +220,10 @@ db_execute("REPLACE INTO settings (name, value) VALUES ('admin_user', '0')"); include_once($config['base_path'] . '/plugins/cloud/setup.php'); plugin_cloud_upgrade(); - $result = array('viewer_realms' => (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM user_auth_realm WHERE user_id = ?', array($viewer))); + $result = array('viewer_realms' => (int) db_fetch_cell_prepared( + 'SELECT COUNT(*) FROM user_auth_realm WHERE user_id = ?', + array($viewer) + )); db_execute("REPLACE INTO settings (name, value) VALUES ('admin_user', '1')"); break; @@ -203,7 +244,10 @@ $tables = array(); -foreach (db_fetch_assoc("SELECT TABLE_NAME AS t FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE 'plugin\\_cloud\\_%' ORDER BY TABLE_NAME") as $row) { +foreach (db_fetch_assoc( + "SELECT TABLE_NAME AS t FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE " . + "'plugin\\_cloud\\_%' ORDER BY TABLE_NAME" +) as $row) { $tables[$row['t']] = (int) db_fetch_cell('SELECT COUNT(*) FROM `' . $row['t'] . '`'); } @@ -212,9 +256,23 @@ 'output' => $output, 'plugin' => db_fetch_row("SELECT status, version FROM plugin_config WHERE directory = 'cloud'"), 'schema' => db_fetch_cell("SELECT value FROM settings WHERE name = 'cloud_schema_version'"), - 'hooks' => array_column(db_fetch_assoc("SELECT hook, status FROM plugin_hooks WHERE name = 'cloud' ORDER BY hook"), 'status', 'hook'), - 'realms' => array_column(db_fetch_assoc("SELECT file, display FROM plugin_realms WHERE plugin = 'cloud' ORDER BY file"), 'display', 'file'), - 'admin' => (int) db_fetch_cell("SELECT COUNT(*) FROM user_auth_realm AS uar INNER JOIN plugin_realms AS pr ON pr.id + 100 = uar.realm_id WHERE pr.plugin = 'cloud' AND uar.user_id = 1"), - 'tracked' => array_column(db_fetch_assoc("SELECT `table` FROM plugin_db_changes WHERE plugin = 'cloud' AND method = 'create' ORDER BY `table`"), 'table'), + 'hooks' => array_column( + db_fetch_assoc("SELECT hook, status FROM plugin_hooks WHERE name = 'cloud' ORDER BY hook"), + 'status', + 'hook' + ), + 'realms' => array_column( + db_fetch_assoc("SELECT file, display FROM plugin_realms WHERE plugin = 'cloud' ORDER BY file"), + 'display', + 'file' + ), + 'admin' => (int) db_fetch_cell( + "SELECT COUNT(*) FROM user_auth_realm AS uar INNER JOIN plugin_realms AS pr ON pr.id + 100 = uar.realm_id WHERE " . + "pr.plugin = 'cloud' AND uar.user_id = 1" + ), + 'tracked' => array_column( + db_fetch_assoc("SELECT `table` FROM plugin_db_changes WHERE plugin = 'cloud' AND method = 'create' ORDER BY `table`"), + 'table' + ), 'tables' => $tables, ), JSON_PRETTY_PRINT) . PHP_EOL; diff --git a/tests/bin/page-check.php b/tests/bin/page-check.php index e0358d2..bdf91a7 100644 --- a/tests/bin/page-check.php +++ b/tests/bin/page-check.php @@ -40,14 +40,26 @@ $pages = array_slice($argv, 2); $password = 'Cloud-' . bin2hex(random_bytes(6)); -db_execute_prepared("UPDATE user_auth SET password = ?, must_change_password = '' WHERE id = 1", array(password_hash($password, PASSWORD_DEFAULT))); +db_execute_prepared( + "UPDATE user_auth SET password = ?, must_change_password = '' WHERE id = 1", + array(password_hash($password, PASSWORD_DEFAULT)) +); $jar = tempnam(sys_get_temp_dir(), 'page'); function page_get($url, $jar, $post = null) { $ch = curl_init($url); - curl_setopt_array($ch, array(CURLOPT_RETURNTRANSFER => true, CURLOPT_COOKIEJAR => $jar, CURLOPT_COOKIEFILE => $jar, CURLOPT_FOLLOWLOCATION => true, CURLOPT_TIMEOUT => 60)); + curl_setopt_array( + $ch, + array( + CURLOPT_RETURNTRANSFER => true, + CURLOPT_COOKIEJAR => $jar, + CURLOPT_COOKIEFILE => $jar, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_TIMEOUT => 60 + ) + ); if ($post !== null) { curl_setopt($ch, CURLOPT_POST, true); @@ -61,7 +73,16 @@ function page_get($url, $jar, $post = null) { list(, $login) = page_get($base . 'index.php', $jar); preg_match('/csrfMagicToken\s*=\s*"([^"]+)"/', $login, $match); -page_get($base . 'index.php', $jar, array('__csrf_magic' => isset($match[1]) ? $match[1] : '', 'action' => 'login', 'login_username' => 'admin', 'login_password' => $password)); +page_get( + $base . 'index.php', + $jar, + array( + '__csrf_magic' => isset($match[1]) ? $match[1] : '', + 'action' => 'login', + 'login_username' => 'admin', + 'login_password' => $password + ) +); $failures = 0; diff --git a/tests/bin/page-permissions.php b/tests/bin/page-permissions.php index 2de6b6d..5df44fc 100644 --- a/tests/bin/page-permissions.php +++ b/tests/bin/page-permissions.php @@ -51,14 +51,25 @@ $failures = 0; $view = (int) db_fetch_cell("SELECT id + 100 FROM plugin_realms WHERE plugin = 'cloud' AND file = 'cloud_health.php'"); -$admin = (int) db_fetch_cell("SELECT id + 100 FROM plugin_realms WHERE plugin = 'cloud' AND file = 'cloud_accounts.php'"); +$admin = (int) db_fetch_cell( + "SELECT id + 100 FROM plugin_realms WHERE plugin = 'cloud' AND file = 'cloud_accounts.php'" +); -db_execute_prepared("UPDATE user_auth SET password = ?, must_change_password = '', password_change = '', enabled = 'on', locked = '', failed_attempts = 0 WHERE id = 1", array(password_hash($password, PASSWORD_DEFAULT))); +db_execute_prepared( + "UPDATE user_auth SET password = ?, must_change_password = '', password_change = '', enabled = 'on', locked = '', " . + "failed_attempts = 0 WHERE id = 1", + array(password_hash($password, PASSWORD_DEFAULT)) +); // Realm 8 is Console access. foreach (array('viewer' => array(8, $view), 'norealm' => array(8)) as $name => $realms) { db_execute_prepared('DELETE FROM user_auth WHERE username = ?', array($name)); - db_execute_prepared("INSERT INTO user_auth (username, password, realm, full_name, must_change_password, password_change, policy_graphs, policy_trees, policy_hosts, policy_graph_templates, enabled) VALUES (?, ?, 0, ?, '', '', 1, 1, 1, 1, 'on')", array($name, password_hash($password, PASSWORD_DEFAULT), $name)); + db_execute_prepared( + "INSERT INTO user_auth (username, password, realm, full_name, must_change_password, password_change, " . + "policy_graphs, policy_trees, policy_hosts, policy_graph_templates, enabled) VALUES (?, ?, 0, ?, '', '', 1, 1, 1, " . + "1, 'on')", + array($name, password_hash($password, PASSWORD_DEFAULT), $name) + ); $id = (int) db_fetch_insert_id(); foreach ($realms as $realm) { @@ -76,7 +87,16 @@ function perm_expect($ok, $message) { function perm_http($url, $jar, $post = null) { $ch = curl_init($url); - curl_setopt_array($ch, array(CURLOPT_RETURNTRANSFER => true, CURLOPT_COOKIEJAR => $jar, CURLOPT_COOKIEFILE => $jar, CURLOPT_FOLLOWLOCATION => true, CURLOPT_TIMEOUT => 60)); + curl_setopt_array( + $ch, + array( + CURLOPT_RETURNTRANSFER => true, + CURLOPT_COOKIEJAR => $jar, + CURLOPT_COOKIEFILE => $jar, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_TIMEOUT => 60 + ) + ); if ($post !== null) { curl_setopt($ch, CURLOPT_POST, true); @@ -97,30 +117,56 @@ function perm_login($user) { $jar = tempnam(sys_get_temp_dir(), 'cloudperm'); list(, $login) = perm_http($root . 'index.php', $jar); - perm_http($root . 'index.php', $jar, array('__csrf_magic' => perm_token($login), 'action' => 'login', 'login_username' => $user, 'login_password' => $password)); + perm_http( + $root . 'index.php', + $jar, + array( + '__csrf_magic' => perm_token($login), + 'action' => 'login', + 'login_username' => $user, + 'login_password' => $password + ) + ); return $jar; } // Markers that only the rendered plugin page contains. -$pages = array('cloud_accounts.php' => 'name="action" value="save"|No cloud accounts yet|linkEditMain', 'cloud_health.php' => 'Cloud Warnings'); - -db_execute_prepared("INSERT INTO plugin_cloud_account (provider, name, credential_source, admin_state) VALUES ('digitalocean', ?, 'vault', 'disabled')", array('Probe')); +$pages = array( + 'cloud_accounts.php' => 'name="action" value="save"|No cloud accounts yet|linkEditMain', + 'cloud_health.php' => 'Cloud Warnings' +); + +db_execute_prepared( + "INSERT INTO plugin_cloud_account (provider, name, credential_source, admin_state) VALUES ('digitalocean', ?, " . + "'vault', 'disabled')", + array('Probe') +); $probe = (int) db_fetch_insert_id(); -foreach (array('admin' => array('cloud_accounts.php' => true, 'cloud_health.php' => true), 'viewer' => array('cloud_accounts.php' => false, 'cloud_health.php' => true), 'norealm' => array('cloud_accounts.php' => false, 'cloud_health.php' => false)) as $user => $expect) { +foreach (array( + 'admin' => array('cloud_accounts.php' => true, 'cloud_health.php' => true), + 'viewer' => array('cloud_accounts.php' => false, 'cloud_health.php' => true), + 'norealm' => array('cloud_accounts.php' => false, 'cloud_health.php' => false) +) as $user => $expect) { $jar = perm_login($user); foreach ($expect as $page => $allowed) { list($code, $body) = perm_http($base . $page, $jar); $shown = preg_match('/' . $pages[$page] . '/', $body) === 1; - perm_expect($shown === $allowed && preg_match('/(Fatal error|Parse error|Warning:|Uncaught)/', $body) !== 1, "$user " . ($allowed ? 'sees' : 'is denied') . " $page (HTTP $code)"); + perm_expect( + $shown === $allowed && preg_match('/(Fatal error|Parse error|Warning:|Uncaught)/', $body) !== 1, + "$user " . ($allowed ? 'sees' : 'is denied') . " $page (HTTP $code)" + ); // Credential state is an account detail for Cloud Admin only. if ($page === 'cloud_health.php' && $allowed) { $credential = strpos($body, 'Credential') !== false; - perm_expect($credential === ($user === 'admin'), "$user " . ($user === 'admin' ? 'sees' : 'does not see') . ' credential state on cloud_health.php'); + perm_expect( + $credential === ($user === 'admin'), + "$user " . ($user === 'admin' ? 'sees' : 'does not see') . ' credential state on cloud_health.php' + ); } } @@ -135,7 +181,10 @@ function perm_login($user) { // The probe's name is markup; every page that prints it must escape it. foreach (array('cloud_accounts.php', 'cloud_accounts.php?action=edit&id=' . $probe) as $page) { list(, $body) = perm_http($base . $page, $jar); - perm_expect(strpos($body, '') === false && strpos($body, '<b id="cloudprobe">') !== false, "$page escapes the account name"); + perm_expect( + strpos($body, '') === false && strpos($body, '<b id="cloudprobe">') !== false, + "$page escapes the account name" + ); } perm_http($base . 'cloud_accounts.php?action=delete&id=' . $probe, $jar); @@ -145,7 +194,11 @@ function perm_login($user) { perm_expect($exists(), 'a delete POST without the csrf-magic token has no effect'); list(, $list) = perm_http($base . 'cloud_accounts.php', $jar); -perm_http($base . 'cloud_accounts.php', $jar, array('__csrf_magic' => perm_token($list), 'action' => 'delete', 'id' => $probe)); +perm_http( + $base . 'cloud_accounts.php', + $jar, + array('__csrf_magic' => perm_token($list), 'action' => 'delete', 'id' => $probe) +); perm_expect(!$exists(), 'the same delete as a POST with the token removes the account'); // A credential saved through the form must come back in no response, no @@ -165,26 +218,45 @@ function perm_login($user) { list($code, $form) = perm_http($base . 'cloud_accounts.php?action=edit', $jar); $responses[] = array('form', $code, $form, 'name="credential"'); list($code, $saved) = perm_http($base . 'cloud_accounts.php', $jar, array( - '__csrf_magic' => perm_token($form), 'action' => 'save', 'id' => 0, 'provider' => 'digitalocean', 'name' => $probeName, 'poller_id' => 1, - 'credential_source' => 'vault', 'credential' => $secret, 'collect_interval' => 300, 'discover_interval' => 3600, 'request_share' => 50, 'enabled' => 'on', + '__csrf_magic' => perm_token($form), 'action' => 'save', 'id' => 0, 'provider' => 'digitalocean', + 'name' => $probeName, 'poller_id' => 1, + 'credential_source' => 'vault', 'credential' => $secret, 'collect_interval' => 300, + 'discover_interval' => 3600, 'request_share' => 50, 'enabled' => 'on', )); $responses[] = array('save', $code, $saved, 'The account was saved.'); $account = (int) db_fetch_cell_prepared('SELECT id FROM plugin_cloud_account WHERE name = ?', array($probeName)); -perm_expect($account > 0 && (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_cloud_secret WHERE account_id = ?', array($account)) === 1, 'an account saved through the form stores its credential in the vault'); - -foreach (array('list' => array('cloud_accounts.php', 'Stored in the vault'), 'edit' => array('cloud_accounts.php?action=edit&id=' . $account, 'A credential is stored.'), 'health' => array('cloud_health.php', $probeName)) as $label => $page) { +perm_expect( + $account > 0 && (int) db_fetch_cell_prepared( + 'SELECT COUNT(*) FROM plugin_cloud_secret WHERE account_id = ?', + array($account) + ) === 1, + 'an account saved through the form stores its credential in the vault' +); + +foreach (array( + 'list' => array('cloud_accounts.php', 'Stored in the vault'), + 'edit' => array('cloud_accounts.php?action=edit&id=' . $account, 'A credential is stored.'), + 'health' => array('cloud_health.php', $probeName) +) as $label => $page) { list($code, $body) = perm_http($base . $page[0], $jar); $responses[] = array($label, $code, $body, $page[1]); } // No driver ships yet, so Verify records the configuration status. -list($code, $verified) = perm_http($base . 'cloud_accounts.php', $jar, array('__csrf_magic' => perm_token($body), 'action' => 'verify', 'id' => $account)); +list($code, $verified) = perm_http( + $base . 'cloud_accounts.php', + $jar, + array('__csrf_magic' => perm_token($body), 'action' => 'verify', 'id' => $account) +); $responses[] = array('verify', $code, $verified, 'The account or its credential is not configured correctly.'); foreach ($responses as $response) { list($label, $code, $body, $marker) = $response; - perm_expect($code === 200 && strpos($body, $marker) !== false, "the $label request succeeded (HTTP $code) and its page shows what it should"); + perm_expect( + $code === 200 && strpos($body, $marker) !== false, + "the $label request succeeded (HTTP $code) and its page shows what it should" + ); } $leaks = array(); @@ -201,7 +273,10 @@ function perm_login($user) { $leaks[] = 'cacti.log'; } -foreach (db_fetch_assoc("SELECT TABLE_NAME AS t FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND (TABLE_NAME LIKE 'plugin\\_cloud\\_%' OR TABLE_NAME = 'settings')") as $table) { +foreach (db_fetch_assoc( + "SELECT TABLE_NAME AS t FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND (TABLE_NAME LIKE " . + "'plugin\\_cloud\\_%' OR TABLE_NAME = 'settings')" +) as $table) { foreach (db_fetch_assoc('SELECT * FROM `' . $table['t'] . '`') as $row) { if (strpos(implode("\0", array_map('strval', $row)), $secret) !== false) { $leaks[] = $table['t']; @@ -209,7 +284,13 @@ function perm_login($user) { } } -perm_expect(count($responses) === 6 && $leaks === array(), 'the credential appears in no response, log, or table' . ($leaks === array() ? '' : ': ' . implode(', ', array_unique($leaks)))); +perm_expect( + count($responses) === 6 && $leaks === array(), + 'the credential appears in no response, log, or table' . ($leaks === array() ? '' : ': ' . implode( + ', ', + array_unique($leaks) + )) +); db_execute("DELETE FROM settings WHERE name = 'cloud_vault_key_file'"); unlink($keyFile); diff --git a/tests/bin/php-guard-check.php b/tests/bin/php-guard-check.php index f738bcb..ffd2c59 100644 --- a/tests/bin/php-guard-check.php +++ b/tests/bin/php-guard-check.php @@ -54,7 +54,10 @@ function guard_state() { 'status' => db_fetch_cell("SELECT status FROM plugin_config WHERE directory = 'cloud'"), 'hooks' => (int) db_fetch_cell("SELECT COUNT(*) FROM plugin_hooks WHERE name = 'cloud'"), 'realms' => (int) db_fetch_cell("SELECT COUNT(*) FROM plugin_realms WHERE plugin = 'cloud'"), - 'tables' => (int) db_fetch_cell("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE 'plugin\\_cloud\\_%'"), + 'tables' => (int) db_fetch_cell( + "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() " + . "AND TABLE_NAME LIKE 'plugin\\_cloud\\_%'" + ), ); } @@ -81,13 +84,19 @@ function guard_call_shims() { api_plugin_hook('poller_bottom'); // Core's own entries (plugins.php) are added by the dispatch; none of ours may be. $dispatched = api_plugin_hook_function('draw_navigation_text', $nav); - guard_expect(is_array($dispatched) && preg_grep('/^cloud/', array_keys($dispatched)) === array(), 'core dispatch of draw_navigation_text adds no cloud entry'); + guard_expect( + is_array($dispatched) && preg_grep('/^cloud/', array_keys($dispatched)) === array(), + 'core dispatch of draw_navigation_text adds no cloud entry' + ); } $supported = version_compare(PHP_VERSION, '8.2.0', '>='); $preexisting = guard_state(); -print 'PHP ' . PHP_VERSION . ', Cacti ' . CACTI_VERSION . ', status ' . var_export($preexisting['status'], true) . ', hooks already registered: ' . $preexisting['hooks'] . PHP_EOL; +print 'PHP ' . PHP_VERSION . ', Cacti ' . CACTI_VERSION . ', status ' . var_export( + $preexisting['status'], + true +) . ', hooks already registered: ' . $preexisting['hooks'] . PHP_EOL; if (!$supported && ($preexisting['status'] == 1 || $preexisting['hooks'] > 0)) { // Enabled under a supported PHP, then PHP was downgraded. Cacti @@ -111,11 +120,20 @@ function guard_call_shims() { guard_expect($state['tables'] === 8, 'all eight plugin tables exist (' . $state['tables'] . ')'); guard_expect($state['hooks'] >= 3 && $state['realms'] === 2, 'hooks and realms are registered'); } else { - guard_expect($state['status'] == 2, 'plugin is left as needing configuration, not enabled (status ' . $state['status'] . ')'); - guard_expect($state['tables'] === 0 && $state['hooks'] === 0 && $state['realms'] === 0, 'no tables, hooks, or realms were created'); + guard_expect( + $state['status'] == 2, + 'plugin is left as needing configuration, not enabled (status ' . $state['status'] . ')' + ); + guard_expect( + $state['tables'] === 0 && $state['hooks'] === 0 && $state['realms'] === 0, + 'no tables, hooks, or realms were created' + ); guard_expect(!class_exists('Somethingwithproof\\Cloud\\Log', false), 'no plugin class was loaded'); - $logged = (int) shell_exec('grep -c ' . escapeshellarg('CLOUD ERROR: The Cloud plugin requires PHP 8.2.0 or later') . ' ' . escapeshellarg(cacti_log_file())); + $logged = (int) shell_exec( + 'grep -c ' . escapeshellarg('CLOUD ERROR: The Cloud plugin requires PHP 8.2.0 or later') + . ' ' . escapeshellarg(cacti_log_file()) + ); guard_expect($logged > 0, 'the refusal naming PHP 8.2.0 was logged'); guard_call_shims(); diff --git a/tests/bootstrap-unit.php b/tests/bootstrap-unit.php index 4a4ae3f..a8b7950 100644 --- a/tests/bootstrap-unit.php +++ b/tests/bootstrap-unit.php @@ -134,7 +134,14 @@ function db_rollback_transaction($db_conn = false) { } if (!function_exists('db_fetch_cell_prepared')) { - function db_fetch_cell_prepared($sql, $params = [], $col_name = '', $log = true, $db_conn = false, $log_function = null) { + function db_fetch_cell_prepared( + $sql, + $params = [], + $col_name = '', + $log = true, + $db_conn = false, + $log_function = null + ) { if (str_contains($sql, '@@in_transaction')) { return $GLOBALS['__cloud_in_tx'] === [] ? 1 : array_shift($GLOBALS['__cloud_in_tx']); } diff --git a/tests/signing-vectors/AwsSigV4.php b/tests/signing-vectors/AwsSigV4.php index 12d0ed6..1e4d86b 100644 --- a/tests/signing-vectors/AwsSigV4.php +++ b/tests/signing-vectors/AwsSigV4.php @@ -26,7 +26,8 @@ final class AwsSigV4 { /** * @param list $headers name and value pairs in request order - * @return array{canonical: string, stringToSign: string, signature: string, authorization: string, addHeaders: array} + * @return array{canonical: string, stringToSign: string, signature: string, authorization: string, + * addHeaders: array} */ public static function sign( string $method, @@ -101,7 +102,8 @@ public static function sign( 'canonical' => $canonical, 'stringToSign' => $stringToSign, 'signature' => $signature, - 'authorization' => "AWS4-HMAC-SHA256 Credential=$accessKey/$scope, SignedHeaders=$signedHeaders, Signature=$signature", + 'authorization' => "AWS4-HMAC-SHA256 Credential=$accessKey/$scope, " + . "SignedHeaders=$signedHeaders, Signature=$signature", 'addHeaders' => $add, ); } diff --git a/tests/signing-vectors/jwt-rs256.php b/tests/signing-vectors/jwt-rs256.php index f7c85d9..0f8b66c 100644 --- a/tests/signing-vectors/jwt-rs256.php +++ b/tests/signing-vectors/jwt-rs256.php @@ -45,7 +45,12 @@ function joined(string $s): string { $jwk = json_decode('{"kty":"RSA",' . joined($m[1]) . '}', true, 4, JSON_THROW_ON_ERROR); preg_match('/(eyJhbGciOiJSUzI1NiJ9\s+\.\s+eyJ[\w\s-]+?)\n\n/s', $a2, $m); $signingInput = joined($m[1]); -preg_match('/BASE64URL\(JWS Signature\) produces this\s+value \(with line breaks for display purposes only\):\s+([\w\s-]+?)\n\n/s', $a2, $m); +preg_match( + '/BASE64URL\(JWS Signature\) produces this\s+value \(with line breaks for display purposes ' . + 'only\):\s+([\w\s-]+?)\n\n/s', + $a2, + $m +); $expected = joined($m[1]); $b64 = static fn (string $s): string => base64_decode(strtr($s, '-_', '+/'), true); @@ -71,13 +76,28 @@ function joined(string $s): string { $checks = array( 'signature equals RFC 7515 A.2' => $b64url($sig) === $expected, - 'openssl_verify accepts RFC value' => openssl_verify($signingInput, $b64($expected), $public, OPENSSL_ALGO_SHA256) === 1, - 'openssl_verify rejects a changed input' => openssl_verify($signingInput . 'x', $b64($expected), $public, OPENSSL_ALGO_SHA256) === 0, + 'openssl_verify accepts RFC value' => openssl_verify( + $signingInput, + $b64($expected), + $public, + OPENSSL_ALGO_SHA256 + ) === 1, + 'openssl_verify rejects a changed input' => openssl_verify( + $signingInput . 'x', + $b64($expected), + $public, + OPENSSL_ALGO_SHA256 + ) === 0, ); $fail = 0; foreach ($checks as $name => $ok) { echo ($ok ? 'pass ' : 'FAIL ') . $name . "\n"; $fail += $ok ? 0 : 1; } -printf("signing input %d bytes, key %d bits, OpenSSL %s\n", strlen($signingInput), openssl_pkey_get_details($key)['bits'], OPENSSL_VERSION_TEXT); +printf( + "signing input %d bytes, key %d bits, OpenSSL %s\n", + strlen($signingInput), + openssl_pkey_get_details($key)['bits'], + OPENSSL_VERSION_TEXT +); exit($fail === 0 ? 0 : 1); diff --git a/tests/signing-vectors/run.php b/tests/signing-vectors/run.php index 79eb3f6..be5f9f5 100644 --- a/tests/signing-vectors/run.php +++ b/tests/signing-vectors/run.php @@ -72,10 +72,19 @@ $dir = $argv[1] ?? ''; $contextFiles = is_dir($dir) ? glob(rtrim($dir, '/') . '/*/context.json') : false; -$found = $contextFiles === false ? array() : array_map(static fn (string $f): string => basename(dirname($f)), $contextFiles); +$found = $contextFiles === false ? array() : array_map( + static fn (string $f): string => basename(dirname($f)), + $contextFiles +); sort($found); if ($found !== EXPECTED_CASES) { - fwrite(STDERR, "not the pinned suite's v4 directory: missing " . implode(', ', array_diff(EXPECTED_CASES, $found)) . '; extra ' . implode(', ', array_diff($found, EXPECTED_CASES)) . "\n"); + fwrite( + STDERR, + "not the pinned suite's v4 directory: missing " . implode( + ', ', + array_diff(EXPECTED_CASES, $found) + ) . '; extra ' . implode(', ', array_diff($found, EXPECTED_CASES)) . "\n" + ); exit(2); } $pass = 0; diff --git a/tests/transport-spike/CurlTransport.php b/tests/transport-spike/CurlTransport.php index a732247..5467afd 100644 --- a/tests/transport-spike/CurlTransport.php +++ b/tests/transport-spike/CurlTransport.php @@ -36,7 +36,14 @@ public function __construct( * @param array $headers * @return array{status: int, headers: array, body: string} */ - public function send(string $method, string $url, array $headers, ?string $body, float $connectTimeout, float $totalTimeout): array { + public function send( + string $method, + string $url, + array $headers, + ?string $body, + float $connectTimeout, + float $totalTimeout + ): array { if (!extension_loaded('curl')) { throw new TransportError('curl_missing'); } @@ -68,7 +75,10 @@ public function send(string $method, string $url, array $headers, ?string $body, CURLOPT_NOSIGNAL => true, CURLOPT_PROTOCOLS => CURLPROTO_HTTPS, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_HEADERFUNCTION => function ($ch, string $line) use (&$responseHeaders, &$headerBytes, &$failure, $maxBytes): int { + CURLOPT_HEADERFUNCTION => function ( + $ch, + string $line + ) use (&$responseHeaders, &$headerBytes, &$failure, $maxBytes): int { $headerBytes += strlen($line); if ($headerBytes > 65536) { $failure = 'headers_too_large'; @@ -118,11 +128,16 @@ public function send(string $method, string $url, array $headers, ?string $body, 60, 77 => 'tls_verify', 51 => 'tls_name', // 28 is both; libcurl names the phase in the message. - 28 => str_starts_with($error, 'Connection timed out') || str_starts_with($error, 'Connection timeout') || str_contains($error, 'SSL connection timeout') ? 'connect_timeout' : 'total_timeout', + 28 => str_starts_with($error, 'Connection timed out') + || str_starts_with($error, 'Connection timeout') + || str_contains($error, 'SSL connection timeout') ? 'connect_timeout' : 'total_timeout', 7 => 'connect_refused', default => 'curl_' . $errno, }; - if ($kind === 'tls_verify' && (str_contains($error, 'does not match') || str_contains($error, 'subject name matches'))) { + if ( + $kind === 'tls_verify' + && (str_contains($error, 'does not match') || str_contains($error, 'subject name matches')) + ) { $kind = 'tls_name'; } throw new TransportError($kind, substr($error, 0, 400)); diff --git a/tests/transport-spike/SocketTransport.php b/tests/transport-spike/SocketTransport.php index 3cbfd75..65e8b8e 100644 --- a/tests/transport-spike/SocketTransport.php +++ b/tests/transport-spike/SocketTransport.php @@ -39,7 +39,14 @@ public function __construct( * @param array $headers * @return array{status: int, headers: array, body: string} */ - public function send(string $method, string $url, array $headers, ?string $body, float $connectTimeout, float $totalTimeout): array { + public function send( + string $method, + string $url, + array $headers, + ?string $body, + float $connectTimeout, + float $totalTimeout + ): array { $deadline = microtime(true) + $totalTimeout; $parts = parse_url($url); if (($parts['scheme'] ?? '') !== 'https' || !isset($parts['host'])) { @@ -51,7 +58,8 @@ public function send(string $method, string $url, array $headers, ?string $body, // A CR or LF in a name or value would let a caller inject headers or a // second request. - $request = "$method $target HTTP/1.1\r\nHost: " . $host . ($port === 443 ? '' : ":$port") . "\r\nConnection: close\r\n"; + $request = "$method $target HTTP/1.1\r\nHost: " . $host . ($port === 443 ? '' : ":$port") + . "\r\nConnection: close\r\n"; foreach ($headers as $name => $value) { if (preg_match('/^[!#$%&\'*+.^_`|~0-9A-Za-z-]+$/', $name) !== 1 || preg_match('/[\r\n\x00]/', $value) === 1) { throw new TransportError('header_rejected'); @@ -240,7 +248,11 @@ private static function dechunk(string $raw): string { $pos = 0; while (true) { $eol = strpos($raw, "\r\n", $pos); - if ($eol === false || preg_match('/^([0-9A-Fa-f]{1,8})(?:;[^\r\n]*)?$/', substr($raw, $pos, $eol - $pos), $m) !== 1) { + if ($eol === false || preg_match( + '/^([0-9A-Fa-f]{1,8})(?:;[^\r\n]*)?$/', + substr($raw, $pos, $eol - $pos), + $m + ) !== 1) { throw new TransportError('malformed', 'chunk size'); } $size = hexdec($m[1]); diff --git a/tests/transport-spike/StreamTransport.php b/tests/transport-spike/StreamTransport.php index 196f1f0..c3f51dd 100644 --- a/tests/transport-spike/StreamTransport.php +++ b/tests/transport-spike/StreamTransport.php @@ -41,7 +41,14 @@ public function __construct( * @param array $headers * @return array{status: int, headers: array, body: string} */ - public function send(string $method, string $url, array $headers, ?string $body, float $connectTimeout, float $totalTimeout): array { + public function send( + string $method, + string $url, + array $headers, + ?string $body, + float $connectTimeout, + float $totalTimeout + ): array { // allow_url_fopen is PHP_INI_SYSTEM, so the plugin can detect it but // not change it at runtime. if (!filter_var(ini_get('allow_url_fopen'), FILTER_VALIDATE_BOOLEAN)) { diff --git a/tests/transport-spike/make-certs.php b/tests/transport-spike/make-certs.php index e9af3df..cdf18fc 100644 --- a/tests/transport-spike/make-certs.php +++ b/tests/transport-spike/make-certs.php @@ -54,7 +54,14 @@ function issue(array $dn, string $section, $signKey, $signCert, string $conf, array $keyOpts): array { $key = openssl_pkey_new($keyOpts); $csr = openssl_csr_new($dn, $key, array('digest_alg' => 'sha256', 'config' => $conf)); - $cert = openssl_csr_sign($csr, $signCert, $signKey ?? $key, 30, array('digest_alg' => 'sha256', 'config' => $conf, 'x509_extensions' => $section), random_int(1, PHP_INT_MAX)); + $cert = openssl_csr_sign( + $csr, + $signCert, + $signKey ?? $key, + 30, + array('digest_alg' => 'sha256', 'config' => $conf, 'x509_extensions' => $section), + random_int(1, PHP_INT_MAX) + ); openssl_x509_export($cert, $certPem); openssl_pkey_export($key, $keyPem, null, array('config' => $conf)); diff --git a/tests/transport-spike/server.php b/tests/transport-spike/server.php index 9f43995..9aeb1e1 100644 --- a/tests/transport-spike/server.php +++ b/tests/transport-spike/server.php @@ -34,7 +34,13 @@ if ($mode === 'noread') { // Completes the TLS handshake, then never reads the request. $ctx = stream_context_create(array('ssl' => array('local_cert' => $argv[3] ?? ''))); - $server = stream_socket_server('ssl://127.0.0.1:' . $port, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx); + $server = stream_socket_server( + 'ssl://127.0.0.1:' . $port, + $errno, + $errstr, + STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, + $ctx + ); $held = array(); while (time() < $deadline) { $conn = @stream_socket_accept($server, 1); @@ -58,7 +64,13 @@ } $ctx = stream_context_create(array('ssl' => array('local_cert' => $argv[3] ?? ''))); -$server = stream_socket_server('ssl://127.0.0.1:' . $port, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx); +$server = stream_socket_server( + 'ssl://127.0.0.1:' . $port, + $errno, + $errstr, + STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, + $ctx +); if ($server === false) { fwrite(STDERR, "listen failed: $errstr\n"); exit(1); @@ -126,7 +138,11 @@ function drip($conn, string $bytes, float $interval, float $seconds): void { switch ($path) { case '/ok': $b = '{"ok":true}'; - send($conn, $ok . "Content-Type: application/json\r\nX-Spike: one\r\nRatelimit-Remaining: 4999\r\nContent-Length: " . strlen($b) . "\r\n\r\n" . $b); + send( + $conn, + $ok . "Content-Type: application/json\r\nX-Spike: one\r\nRatelimit-Remaining: 4999\r\n" + . "Content-Length: " . strlen($b) . "\r\n\r\n" . $b + ); break; case '/head': // Headers only, with a length the body never sends: correct for @@ -146,7 +162,12 @@ function drip($conn, string $bytes, float $interval, float $seconds): void { send($conn, $ok . 'Content-Length: ' . strlen($b) . "\r\n\r\n" . $b); break; case '/redirect': - send($conn, "HTTP/1.1 302 Found\r\nLocation: https://127.0.0.1:$port/redirect-target\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); + send( + $conn, + "HTTP/1.1 302 Found\r\n" + . "Location: https://127.0.0.1:$port/redirect-target\r\n" + . "Content-Length: 0\r\nConnection: close\r\n\r\n" + ); break; case '/redirect-target': send($conn, $ok . "Content-Length: 6\r\n\r\nfollow"); @@ -185,7 +206,10 @@ function drip($conn, string $bytes, float $interval, float $seconds): void { break; case '/huge-header': $n = (int) ($query['n'] ?? 0); - send($conn, "HTTP/1.1 200 OK\r\nConnection: close\r\nX-Huge: " . str_repeat('h', $n) . "\r\nContent-Length: 2\r\n\r\nok"); + send( + $conn, + "HTTP/1.1 200 OK\r\nConnection: close\r\nX-Huge: " . str_repeat('h', $n) . "\r\nContent-Length: 2\r\n\r\nok" + ); break; case '/many-headers': $n = (int) ($query['n'] ?? 0); @@ -202,7 +226,10 @@ function drip($conn, string $bytes, float $interval, float $seconds): void { } break; case '/early-hints': - send($conn, "HTTP/1.1 103 Early Hints\r\nLink: ; rel=preload\r\n\r\n" . $ok . "Content-Length: 5\r\n\r\nfinal"); + send( + $conn, + "HTTP/1.1 103 Early Hints\r\nLink: ; rel=preload\r\n\r\n" . $ok . "Content-Length: 5\r\n\r\nfinal" + ); break; case '/bad-terminator': // Last chunk without the empty line that ends the trailer section. @@ -212,7 +239,10 @@ function drip($conn, string $bytes, float $interval, float $seconds): void { send($conn, $ok . "Transfer-Encoding: chunked\r\n\r\nzz\r\nhello\r\n0\r\n\r\n"); break; case '/dup-length': - send($conn, "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 2\r\nContent-Length: 40\r\n\r\nok" . str_repeat('x', 38)); + send( + $conn, + "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 2\r\nContent-Length: 40\r\n\r\nok" . str_repeat('x', 38) + ); break; case '/header-flood': // 64 MiB of header lines, sent as fast as the client reads. diff --git a/tests/transport-spike/spike.php b/tests/transport-spike/spike.php index c5d3bf7..e30fe3d 100644 --- a/tests/transport-spike/spike.php +++ b/tests/transport-spike/spike.php @@ -111,18 +111,38 @@ function expectError(callable $call, string $kind, ?float $maxSeconds = null): a $get = fn (string $url) => fn () => $t->send('GET', $url, array(), null, $connectTimeout, $totalTimeout); -check('trusted certificate', 'request succeeds, status and headers readable', function () use ($t, $base, $connectTimeout, $totalTimeout) { +check('trusted certificate', 'request succeeds, status and headers readable', function () use ( + $t, + $base, + $connectTimeout, + $totalTimeout +) { $r = $t->send('GET', "$base/ok", array('Accept' => 'application/json'), null, $connectTimeout, $totalTimeout); - $pass = $r['status'] === 200 && $r['body'] === '{"ok":true}' && ($r['headers']['x-spike'] ?? '') === 'one' && ($r['headers']['ratelimit-remaining'] ?? '') === '4999'; + $pass = $r['status'] === 200 && $r['body'] === '{"ok":true}' && ($r['headers']['x-spike'] ?? '') === 'one' + && ($r['headers']['ratelimit-remaining'] ?? '') === '4999'; return array("status {$r['status']}, x-spike={$r['headers']['x-spike']}, body {$r['body']}", $pass); }); -check('untrusted certificate', 'refused before any request is sent', fn () => expectError($get("https://127.0.0.1:$self/ok"), 'tls_verify')); - -check('host name mismatch', 'refused before any request is sent', fn () => expectError($get("https://127.0.0.1:$wrong/ok"), 'tls_name')); - -check('redirect', 'not followed; target never requested', function () use ($t, $base, $get, $connectTimeout, $totalTimeout) { +check( + 'untrusted certificate', + 'refused before any request is sent', + fn () => expectError($get("https://127.0.0.1:$self/ok"), 'tls_verify') +); + +check( + 'host name mismatch', + 'refused before any request is sent', + fn () => expectError($get("https://127.0.0.1:$wrong/ok"), 'tls_name') +); + +check('redirect', 'not followed; target never requested', function () use ( + $t, + $base, + $get, + $connectTimeout, + $totalTimeout +) { $t->send('GET', "$base/log", array(), null, $connectTimeout, $totalTimeout); [$observed, $pass] = expectError($get("$base/redirect"), 'redirect_refused'); $log = json_decode($t->send('GET', "$base/log", array(), null, $connectTimeout, $totalTimeout)['body'], true); @@ -131,27 +151,72 @@ function expectError(callable $call, string $kind, ?float $maxSeconds = null): a return array($observed . '; server log ' . json_encode($log), $pass && !$followed); }); -check('HTTP error body', '4xx status and body returned to the caller', function () use ($t, $base, $connectTimeout, $totalTimeout) { +check('HTTP error body', '4xx status and body returned to the caller', function () use ( + $t, + $base, + $connectTimeout, + $totalTimeout +) { $r = $t->send('GET', "$base/error", array(), null, $connectTimeout, $totalTimeout); - return array("status {$r['status']}, body {$r['body']}", $r['status'] === 403 && str_contains($r['body'], 'missing scope')); + return array( + "status {$r['status']}, body {$r['body']}", + $r['status'] === 403 && str_contains($r['body'], 'missing scope') + ); }); -check('POST body and headers', 'method, headers and body reach the server unchanged', function () use ($t, $base, $connectTimeout, $totalTimeout) { +check('POST body and headers', 'method, headers and body reach the server unchanged', function () use ( + $t, + $base, + $connectTimeout, + $totalTimeout +) { $form = 'Action=GetMetricData&Version=2010-08-01'; - $r = $t->send('POST', "$base/echo", array('Content-Type' => 'application/x-www-form-urlencoded', 'X-Amz-Date' => '20261114T000000Z'), $form, $connectTimeout, $totalTimeout); + $r = $t->send( + 'POST', + "$base/echo", + array('Content-Type' => 'application/x-www-form-urlencoded', 'X-Amz-Date' => '20261114T000000Z'), + $form, + $connectTimeout, + $totalTimeout + ); $e = json_decode($r['body'], true); $pass = $e['method'] === 'POST' && $e['body'] === $form && $e['headers']['x-amz-date'] === '20261114T000000Z' && $e['headers']['content-length'] === (string) strlen($form) && !isset($e['headers']['accept-encoding']); - return array('server saw ' . json_encode(array('method' => $e['method'], 'content-length' => $e['headers']['content-length'] ?? null, 'host' => $e['headers']['host'] ?? null)), $pass); + return array( + 'server saw ' . json_encode(array( + 'method' => $e['method'], + 'content-length' => $e['headers']['content-length'] ?? null, + 'host' => $e['headers']['host'] ?? null + )), + $pass + ); }); -check('PUT with empty body', 'IMDSv2 token request shape (PUT, no body) is sent', function () use ($t, $base, $connectTimeout, $totalTimeout) { - $r = $t->send('PUT', "$base/echo", array('X-aws-ec2-metadata-token-ttl-seconds' => '21600'), null, $connectTimeout, $totalTimeout); +check('PUT with empty body', 'IMDSv2 token request shape (PUT, no body) is sent', function () use ( + $t, + $base, + $connectTimeout, + $totalTimeout +) { + $r = $t->send( + 'PUT', + "$base/echo", + array('X-aws-ec2-metadata-token-ttl-seconds' => '21600'), + null, + $connectTimeout, + $totalTimeout + ); $e = json_decode($r['body'], true); - return array('server saw ' . json_encode(array('method' => $e['method'], 'content-length' => $e['headers']['content-length'] ?? null)), $e['method'] === 'PUT'); + return array( + 'server saw ' . json_encode(array( + 'method' => $e['method'], + 'content-length' => $e['headers']['content-length'] ?? null + )), + $e['method'] === 'PUT' + ); }); check('chunked response', 'decoded body returned', function () use ($t, $base, $connectTimeout, $totalTimeout) { @@ -162,13 +227,29 @@ function expectError(callable $call, string $kind, ?float $maxSeconds = null): a // The server declares the size and withholds the body, so only a refusal // from the header can finish inside the limit. -check('oversized, Content-Length declared', 'refused from the header without reading the body', fn () => expectError($get($fresh() . "/big-withheld?n=20000000"), 'too_large', 1.0)); - -check('oversized, no Content-Length', 'cut off at the cap', fn () => expectError($get("$base/big?n=20000000&len=0"), 'too_large', 2.0)); - -check('stalled body', 'aborted at the total timeout', fn () => expectError($get($fresh() . "/stall"), 'total_timeout', $totalTimeout + 0.5)); - -check('slow body (1 byte per 0.5 s)', 'aborted at the total timeout', fn () => expectError($get($fresh() . "/slow-body"), 'total_timeout', $totalTimeout + 0.5)); +check( + 'oversized, Content-Length declared', + 'refused from the header without reading the body', + fn () => expectError($get($fresh() . "/big-withheld?n=20000000"), 'too_large', 1.0) +); + +check( + 'oversized, no Content-Length', + 'cut off at the cap', + fn () => expectError($get("$base/big?n=20000000&len=0"), 'too_large', 2.0) +); + +check( + 'stalled body', + 'aborted at the total timeout', + fn () => expectError($get($fresh() . "/stall"), 'total_timeout', $totalTimeout + 0.5) +); + +check( + 'slow body (1 byte per 0.5 s)', + 'aborted at the total timeout', + fn () => expectError($get($fresh() . "/slow-body"), 'total_timeout', $totalTimeout + 0.5) +); check('slow headers (1 byte per 0.5 s)', 'aborted at the total timeout', function () use ($get, $totalTimeout) { $start = microtime(true); @@ -176,7 +257,10 @@ function expectError(callable $call, string $kind, ?float $maxSeconds = null): a $r = $get($GLOBALS['fresh']() . '/slow-headers')(); $elapsed = microtime(true) - $start; - return array(sprintf('completed with status %d after %.1f s', $r['status'], $elapsed), $elapsed <= $totalTimeout + 0.5); + return array( + sprintf('completed with status %d after %.1f s', $r['status'], $elapsed), + $elapsed <= $totalTimeout + 0.5 + ); } catch (TransportError $e) { $elapsed = microtime(true) - $start; @@ -184,7 +268,11 @@ function expectError(callable $call, string $kind, ?float $maxSeconds = null): a } }); -check('TLS handshake never answered', 'aborted within the connect timeout', function () use ($get, $silent, $connectTimeout) { +check('TLS handshake never answered', 'aborted within the connect timeout', function () use ( + $get, + $silent, + $connectTimeout +) { $start = microtime(true); [$observed] = expectError($get("https://127.0.0.1:$silent/ok"), 'connect_timeout'); $elapsed = microtime(true) - $start; @@ -192,7 +280,11 @@ function expectError(callable $call, string $kind, ?float $maxSeconds = null): a return array($observed, $elapsed <= $connectTimeout + 0.5); }); -check('total timeout shorter than connect timeout', 'aborted at the total timeout', function () use ($t, $silent, $connectTimeout) { +check('total timeout shorter than connect timeout', 'aborted at the total timeout', function () use ( + $t, + $silent, + $connectTimeout +) { $start = microtime(true); try { $t->send('GET', "https://127.0.0.1:$silent/ok", array(), null, $connectTimeout, 0.25); @@ -211,10 +303,22 @@ function expectError(callable $call, string $kind, ?float $maxSeconds = null): a return array(sprintf('%s after %.2f s', $observed, $elapsed), $timedOut && $elapsed >= 0.2 && $elapsed <= 0.75); }); -check('peer stops reading the request', 'aborted at the total timeout', function () use ($t, $noread, $connectTimeout, $totalTimeout) { +check('peer stops reading the request', 'aborted at the total timeout', function () use ( + $t, + $noread, + $connectTimeout, + $totalTimeout +) { $start = microtime(true); try { - $t->send('POST', "https://127.0.0.1:$noread/echo", array('Content-Type' => 'application/octet-stream'), str_repeat('u', 32 * 1048576), $connectTimeout, $totalTimeout); + $t->send( + 'POST', + "https://127.0.0.1:$noread/echo", + array('Content-Type' => 'application/octet-stream'), + str_repeat('u', 32 * 1048576), + $connectTimeout, + $totalTimeout + ); $observed = 'no error'; $kind = null; } catch (TransportError $e) { @@ -225,10 +329,16 @@ function expectError(callable $call, string $kind, ?float $maxSeconds = null): a // The handshake completes at once, so only a write held until the total // timeout can produce total_timeout after waiting most of the budget. - return array(sprintf('%s after %.1f s', $observed, $elapsed), $kind === 'total_timeout' && $elapsed >= $totalTimeout - 0.5 && $elapsed <= $totalTimeout + 0.5); + return array( + sprintf('%s after %.1f s', $observed, $elapsed), + $kind === 'total_timeout' && $elapsed >= $totalTimeout - 0.5 && $elapsed <= $totalTimeout + 0.5 + ); }); -check('connect to an address that drops packets', 'aborted within the connect timeout', function () use ($get, $connectTimeout) { +check('connect to an address that drops packets', 'aborted within the connect timeout', function () use ( + $get, + $connectTimeout +) { $start = microtime(true); [$observed] = expectError($get('https://192.0.2.1/ok'), 'connect_timeout'); $elapsed = microtime(true) - $start; @@ -236,7 +346,12 @@ function expectError(callable $call, string $kind, ?float $maxSeconds = null): a return array($observed, $elapsed <= $connectTimeout + 0.5); }); -check('1 MiB response header', 'refused or bounded; no unbounded memory', function () use ($t, $fresh, $connectTimeout, $totalTimeout) { +check('1 MiB response header', 'refused or bounded; no unbounded memory', function () use ( + $t, + $fresh, + $connectTimeout, + $totalTimeout +) { // The peak is reset so an earlier case cannot hide this one's growth. memory_reset_peak_usage(); $before = memory_get_usage(); @@ -266,7 +381,12 @@ function expectError(callable $call, string $kind, ?float $maxSeconds = null): a return array($observed . sprintf('; peak memory grew %.1f MiB', $grew / 1048576), $grew < 4 * 1048576); }); -check('proxy environment variables', 'ignored; the request goes direct', function () use ($t, $base, $connectTimeout, $totalTimeout) { +check('proxy environment variables', 'ignored; the request goes direct', function () use ( + $t, + $base, + $connectTimeout, + $totalTimeout +) { putenv('HTTPS_PROXY=http://127.0.0.1:9'); putenv('https_proxy=http://127.0.0.1:9'); putenv('ALL_PROXY=http://127.0.0.1:9'); @@ -278,12 +398,24 @@ function expectError(callable $call, string $kind, ?float $maxSeconds = null): a return array("status {$r['status']} with proxy variables pointing at a closed port", $r['status'] === 200); }); -check('allow_url_fopen=0', 'stream: detected and reported; socket: request still succeeds', function () use ($certs, $good, $class) { - $code = 'require ' . var_export(__DIR__ . '/SocketTransport.php', true) . '; require ' . var_export(__DIR__ . '/CurlTransport.php', true) . ';' +check('allow_url_fopen=0', 'stream: detected and reported; socket: request still succeeds', function () use ( + $certs, + $good, + $class +) { + $code = 'require ' . var_export( + __DIR__ . '/SocketTransport.php', + true + ) . '; require ' . var_export(__DIR__ . '/CurlTransport.php', true) . ';' . '$t = new ' . $class . '(' . var_export("$certs/ca.pem", true) . ');' - . 'try { $r = $t->send("GET", "https://127.0.0.1:' . $good . '/ok", array(), null, 2, 4); echo "sent:", $r["status"]; } catch (TransportError $e) { echo $e->kind; }' + . 'try { $r = $t->send("GET", "https://127.0.0.1:' . $good . '/ok", array(), null, 2, 4); ' + . 'echo "sent:", $r["status"]; } catch (TransportError $e) { echo $e->kind; }' . 'echo @fopen("https://127.0.0.1:' . $good . '/ok", "rb") === false ? " fopen:refused" : " fopen:opened";'; - $p = proc_open(array(PHP_BINARY, '-d', 'allow_url_fopen=0', '-r', $code), array(1 => array('pipe', 'w'), 2 => array('pipe', 'w')), $pipes); + $p = proc_open( + array(PHP_BINARY, '-d', 'allow_url_fopen=0', '-r', $code), + array(1 => array('pipe', 'w'), 2 => array('pipe', 'w')), + $pipes + ); $out = trim(stream_get_contents($pipes[1]) . stream_get_contents($pipes[2])); proc_close($p); $expect = $class === 'StreamTransport' ? 'allow_url_fopen_off fopen:refused' : 'sent:200 fopen:refused'; @@ -291,13 +423,26 @@ function expectError(callable $call, string $kind, ?float $maxSeconds = null): a return array($out, $out === $expect); }); -check('103 Early Hints before the final response', 'final status and body returned', function () use ($t, $base, $connectTimeout, $totalTimeout) { +check('103 Early Hints before the final response', 'final status and body returned', function () use ( + $t, + $base, + $connectTimeout, + $totalTimeout +) { $r = $t->send('GET', "$base/early-hints", array(), null, $connectTimeout, $totalTimeout); - return array('status ' . $r['status'] . ', body ' . json_encode($r['body']), $r['status'] === 200 && $r['body'] === 'final'); + return array( + 'status ' . $r['status'] . ', body ' . json_encode($r['body']), + $r['status'] === 200 && $r['body'] === 'final' + ); }); -check('chunked body without its final empty line', 'reported as an error, not returned as data', function () use ($t, $fresh, $connectTimeout, $totalTimeout) { +check('chunked body without its final empty line', 'reported as an error, not returned as data', function () use ( + $t, + $fresh, + $connectTimeout, + $totalTimeout +) { try { $r = $t->send('GET', $fresh() . '/bad-terminator', array(), null, $connectTimeout, $totalTimeout); @@ -307,7 +452,12 @@ function expectError(callable $call, string $kind, ?float $maxSeconds = null): a } }); -check('malformed chunk size', 'reported as an error, not returned as data', function () use ($t, $fresh, $connectTimeout, $totalTimeout) { +check('malformed chunk size', 'reported as an error, not returned as data', function () use ( + $t, + $fresh, + $connectTimeout, + $totalTimeout +) { try { $r = $t->send('GET', $fresh() . '/bad-chunk', array(), null, $connectTimeout, $totalTimeout); @@ -327,7 +477,12 @@ function expectError(callable $call, string $kind, ?float $maxSeconds = null): a } }); -check('64 MiB of response headers', 'bounded; refused without buffering it all', function () use ($t, $fresh, $connectTimeout, $totalTimeout) { +check('64 MiB of response headers', 'bounded; refused without buffering it all', function () use ( + $t, + $fresh, + $connectTimeout, + $totalTimeout +) { // The peak is reset so an earlier case cannot hide this one's growth. memory_reset_peak_usage(); $before = memory_get_usage(); @@ -342,7 +497,12 @@ function expectError(callable $call, string $kind, ?float $maxSeconds = null): a return array($observed . sprintf('; peak memory grew %.1f MiB', $grew / 1048576), $grew < 4 * 1048576); }); -check('CRLF in a request header value', 'refused before sending', function () use ($t, $base, $connectTimeout, $totalTimeout) { +check('CRLF in a request header value', 'refused before sending', function () use ( + $t, + $base, + $connectTimeout, + $totalTimeout +) { try { $r = $t->send('GET', "$base/echo", array('X-Test' => "a\r\nX-Injected: 1"), null, $connectTimeout, $totalTimeout); $e = json_decode($r['body'], true);