diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml new file mode 100644 index 0000000..422042c --- /dev/null +++ b/.github/workflows/plugin-ci-workflow.yml @@ -0,0 +1,424 @@ +# SPDX-FileCopyrightText: 2026 Thomas Vincent +# SPDX-License-Identifier: GPL-2.0-or-later +# +# This file is part of plugin_cloud, a plugin for Cacti. +# https://github.com/somethingwithproof/plugin_cloud +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the Free +# Software Foundation; either version 2 of the License, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +# more details. + +# Follows plugin_smokeping and the maintained plugins (servcheck, webseer, +# monitor): Cacti checked out with this plugin under plugins/, a MariaDB +# service, Cacti installed from its CLI, the plugin installed with +# plugin_manage.php, and Pest from the locked shared plugin harness. The test +# harness choice is pending maintainers in #12; this matches what maintained +# plugins use today. +# +# `ci-ok` is the one check branch protection needs to name. + +name: CI + +on: + push: + branches: + - main + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + # Cacti includes setup.php on whatever PHP a 1.2.31 site runs, so the entry + # points must parse on PHP 8.0 even though the plugin refuses to run below + # 8.2. + entry-point-lint: + name: PHP 8.0 entry point lint + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Checkout plugin + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install PHP 8.0 + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: '8.0' + coverage: none + + - name: Lint entry points + run: | + set -euo pipefail + php -v + for f in *.php include/*.php locales/*.php tests/bin/*.php; do + php -l "$f" + done + + integration-test: + name: PHP ${{ matrix.php }} on Cacti ${{ matrix.cacti }} + runs-on: ubuntu-latest + timeout-minutes: 30 + + strategy: + fail-fast: false + matrix: + php: ['8.2', '8.3', '8.4', '8.5'] + cacti: ['release/1.2.31', '1.2.x'] + + services: + mariadb: + image: mariadb:11.8@sha256:6422478cb8e159f080fb1d8ccf65101e26fe51385787fde7d16c3b165a331f15 + env: + MYSQL_ROOT_PASSWORD: cactiroot + MYSQL_DATABASE: cacti + MYSQL_USER: cactiuser + MYSQL_PASSWORD: cactiuser + ports: + - 3306:3306 + options: >- + --health-cmd="mariadb-admin ping" + --health-interval=10s + --health-timeout=5s + --health-retries=3 + + steps: + - name: Checkout Cacti + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + repository: Cacti/cacti + ref: ${{ matrix.cacti }} + path: cacti + + - name: Checkout cloud plugin + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + path: cacti/plugins/cloud + + - name: Install PHP ${{ matrix.php }} + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: ${{ matrix.php }} + tools: composer:2.10.3, phpstan:2.3.5 + extensions: intl, mysql, gd, ldap, gmp, xml, json, mbstring, openssl, snmp + ini-values: "post_max_size=256M, max_execution_time=60, date.timezone=America/New_York" + coverage: none + + - name: Install system dependencies + run: | + sudo apt-get update + # Ubuntu 26.04's mysql client rejects the DELIMITER line at the top of + # Cacti's cacti.sql; MariaDB's client loads it. + sudo apt-get install -y rrdtool gettext mariadb-client + + # Core's release archives exclude tests/, so fetch the shared harness lock + # at the same immutable revision the maintained plugins pin. + - name: Checkout shared CI tooling + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: Cacti/cacti + ref: f3ff777992875740e4665fedfe2eff8335f5b894 + persist-credentials: false + path: ci-tools + sparse-checkout: | + tests/tools/plugin-harness + + - name: Install the locked Pest harness + run: | + set -euo pipefail + harness="$RUNNER_TEMP/cacti-plugin-harness" + mkdir -p "$harness" + cp ci-tools/tests/tools/plugin-harness/composer.json ci-tools/tests/tools/plugin-harness/composer.lock "$harness/" + composer --working-dir="$harness" validate --strict + composer --working-dir="$harness" install --no-interaction --no-progress --prefer-dist + echo "CACTI_PEST_BIN=$harness/vendor/bin/pest" >> "$GITHUB_ENV" + + - name: Initialize Cacti database + run: | + echo -e "[client]\nuser = root\npassword = cactiroot\nhost = 127.0.0.1\n" > ~/.my.cnf + chmod 600 ~/.my.cnf + mariadb -e "CREATE USER IF NOT EXISTS 'cactiuser'@'127.0.0.1' IDENTIFIED BY 'cactiuser';" + mariadb -e "GRANT ALL PRIVILEGES ON cacti.* TO 'cactiuser'@'127.0.0.1';" + mariadb -e "GRANT SELECT ON mysql.time_zone_name TO 'cactiuser'@'127.0.0.1';" + mariadb -e "FLUSH PRIVILEGES;" + mariadb cacti < cacti/cacti.sql + mariadb -e "INSERT INTO settings (name, value) VALUES ('path_php_binary', '$(command -v php)')" cacti + + - name: Create Cacti config.php + run: | + sed -r "s/localhost/127.0.0.1/g" cacti/include/config.php.dist > cacti/include/config.php + + - name: Install Cacti via CLI + working-directory: cacti + run: php cli/install_cacti.php --accept-eula --install --force + + - name: Run unit tests + working-directory: cacti/plugins/cloud + run: '"$CACTI_PEST_BIN" --configuration=phpunit.xml' + + # Installs, upgrades, and uninstalls the plugin through Cacti's own + # plugin API, so it runs before the plugin is installed for the poller. + - name: Run lifecycle integration tests + working-directory: cacti/plugins/cloud + env: + CACTI_PATH: ${{ github.workspace }}/cacti + CLOUD_TEST_DATABASE: disposable + run: '"$CACTI_PEST_BIN" --configuration=phpunit-integration.xml' + + # The integration tests provoke refusals that the plugin logs as errors, + # such as a schema downgrade. Keep their log apart so the error check + # below covers the install and the poller run. + - name: Set the integration tests' log aside + if: always() + run: | + if [ -f cacti/log/cacti.log ]; then + mv cacti/log/cacti.log cacti/log/integration.log + fi + + - name: Install and enable the plugin + working-directory: cacti + run: php plugins/cloud/tests/bin/php-guard-check.php + + # Against the minimum supported release only: the 1.2.x branch's + # docblocks give PDO connections as resources and mistype some + # parameters, which PHPStan reports at every call site. + - name: Run PHPStan + if: matrix.cacti == 'release/1.2.31' + working-directory: cacti/plugins/cloud + env: + CACTI_PATH: ${{ github.workspace }}/cacti + run: phpstan analyse -c phpstan.neon --no-progress + + - name: Verify translation template and catalogs + working-directory: cacti/plugins/cloud + run: sh locales/build_gettext.sh --check + + - name: Run Cacti poller + working-directory: cacti + run: | + php poller.php --poller=1 --force --debug + grep -q "SYSTEM STATS" log/cacti.log + + # poller_bottom starts the collector in the background; run it once in + # the foreground too, so its exit status and log lines are checked. + - name: Run the cloud collector + working-directory: cacti + run: php plugins/cloud/poller_cloud.php --poller=1 + + - name: Check page permissions and POST-only actions + working-directory: cacti + env: + CLOUD_TEST_DATABASE: disposable + run: | + php -S 127.0.0.1:8080 -t "$GITHUB_WORKSPACE" > "$RUNNER_TEMP/php-server.log" 2>&1 & + for _ in 1 2 3 4 5 6 7 8 9 10; do + curl -fsS -o /dev/null http://127.0.0.1:8080/cacti/index.php && break + sleep 1 + done + php plugins/cloud/tests/bin/page-permissions.php http://127.0.0.1:8080/cacti/ + if grep -E "Fatal error|Warning:|Uncaught" "$RUNNER_TEMP/php-server.log"; then + exit 1 + fi + + - name: Check Cacti log for errors + if: always() + run: | + if [ -f cacti/log/integration.log ]; then + echo "== integration tests (not checked)" + cat cacti/log/integration.log + fi + if [ -f cacti/log/cacti.log ]; then + echo "== install and poller run" + cat cacti/log/cacti.log + if grep -E "FATAL:|ERROR:|WARNING:" cacti/log/cacti.log; then + exit 1 + fi + fi + + # A 1.2.31 site may still run PHP 8.1. Enabling the plugin there must be + # refused with a message and leave Cacti working, both on a fresh install + # and after an upgrade-in-place left the plugin's hooks registered. + php-guard: + name: Refusal on PHP 8.1 with Cacti 1.2.31 + runs-on: ubuntu-latest + timeout-minutes: 20 + + services: + mariadb: + image: mariadb:11.8@sha256:6422478cb8e159f080fb1d8ccf65101e26fe51385787fde7d16c3b165a331f15 + env: + MYSQL_ROOT_PASSWORD: cactiroot + MYSQL_DATABASE: cacti + MYSQL_USER: cactiuser + MYSQL_PASSWORD: cactiuser + ports: + - 3306:3306 + options: >- + --health-cmd="mariadb-admin ping" + --health-interval=10s + --health-timeout=5s + --health-retries=3 + + steps: + - name: Checkout Cacti + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + repository: Cacti/cacti + ref: release/1.2.31 + path: cacti + + - name: Checkout cloud plugin + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + path: cacti/plugins/cloud + + - name: Install system dependencies + run: | + sudo apt-get update + sudo apt-get install -y rrdtool mariadb-client + + - name: Install PHP 8.1 + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: '8.1' + extensions: intl, mysql, gd, ldap, gmp, xml, json, mbstring, openssl, snmp + ini-values: "date.timezone=America/New_York" + coverage: none + + - name: Initialize Cacti database + run: | + echo -e "[client]\nuser = root\npassword = cactiroot\nhost = 127.0.0.1\n" > ~/.my.cnf + chmod 600 ~/.my.cnf + mariadb -e "CREATE USER IF NOT EXISTS 'cactiuser'@'127.0.0.1' IDENTIFIED BY 'cactiuser';" + mariadb -e "GRANT ALL PRIVILEGES ON cacti.* TO 'cactiuser'@'127.0.0.1';" + mariadb -e "GRANT SELECT ON mysql.time_zone_name TO 'cactiuser'@'127.0.0.1';" + mariadb -e "FLUSH PRIVILEGES;" + mariadb cacti < cacti/cacti.sql + sed -r "s/localhost/127.0.0.1/g" cacti/include/config.php.dist > cacti/include/config.php + + - name: Install Cacti via CLI + working-directory: cacti + run: php cli/install_cacti.php --accept-eula --install --force + + - name: Install is refused on PHP 8.1 + working-directory: cacti + run: php plugins/cloud/tests/bin/php-guard-check.php + + - name: Install PHP 8.2 + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: '8.2' + extensions: intl, mysql, gd, ldap, gmp, xml, json, mbstring, openssl, snmp + ini-values: "date.timezone=America/New_York" + coverage: none + + - name: Install succeeds on PHP 8.2 + working-directory: cacti + run: php plugins/cloud/tests/bin/php-guard-check.php + + - name: Install PHP 8.1 again + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: '8.1' + extensions: intl, mysql, gd, ldap, gmp, xml, json, mbstring, openssl, snmp + ini-values: "date.timezone=America/New_York" + coverage: none + + - name: Registered hooks stay quiet on PHP 8.1 + working-directory: cacti + run: php plugins/cloud/tests/bin/php-guard-check.php + + # The poller dispatches poller_bottom and loads every enabled plugin's + # setup.php, as each page does through include/global.php. + - name: Cacti's poller still runs on PHP 8.1 + working-directory: cacti + run: | + php poller.php --poller=1 --force --debug + grep -q "SYSTEM STATS" log/cacti.log + + # Every page includes each enabled plugin's setup.php and runs its + # hooks, so the core pages must keep loading, and the plugin's own pages + # must show the refusal instead of failing. + - name: Core pages still load on PHP 8.1 + working-directory: cacti + env: + CLOUD_TEST_DATABASE: disposable + CLOUD_EXPECT_REFUSAL: '1' + run: | + php -S 127.0.0.1:8080 -t "$GITHUB_WORKSPACE" > "$RUNNER_TEMP/php-server.log" 2>&1 & + for _ in 1 2 3 4 5 6 7 8 9 10; do + curl -fsS -o /dev/null http://127.0.0.1:8080/cacti/index.php && break + sleep 1 + done + php plugins/cloud/tests/bin/page-check.php http://127.0.0.1:8080/cacti/ \ + index.php host.php graph_view.php graphs.php data_sources.php plugins.php \ + settings.php utilities.php user_admin.php \ + plugins/cloud/cloud_health.php plugins/cloud/cloud_accounts.php + if grep -E "Fatal error|Parse error|Uncaught" "$RUNNER_TEMP/php-server.log"; then + exit 1 + fi + + workflow-lint: + name: Workflow lint + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Checkout plugin + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Lint the workflows with actionlint and zizmor + env: + GH_TOKEN: ${{ github.token }} + run: sh tests/lint-workflows.sh + + reuse: + name: REUSE compliance + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Checkout plugin + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Lint licensing metadata + run: pipx run --spec 'reuse[charset-normalizer]==6.3.0' reuse lint + + ci-ok: + name: ci-ok + if: ${{ always() }} + needs: + - entry-point-lint + - integration-test + - php-guard + - workflow-lint + - reuse + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: {} + steps: + - name: Require every job to have succeeded + env: + NEEDS: ${{ toJSON(needs) }} + run: | + set -euo pipefail + echo "$NEEDS" | jq -r 'to_entries[] | "\(.key): \(.value.result)"' + echo "$NEEDS" | jq -e 'all(.[]; .result == "success")' >/dev/null diff --git a/INFO b/INFO new file mode 100644 index 0000000..53d6c94 --- /dev/null +++ b/INFO @@ -0,0 +1,25 @@ +; SPDX-FileCopyrightText: 2026 Thomas Vincent +; SPDX-License-Identifier: GPL-2.0-or-later +; +; This file is part of plugin_cloud, a plugin for Cacti. +; https://github.com/somethingwithproof/plugin_cloud +; +; This program is free software; you can redistribute it and/or modify it +; under the terms of the GNU General Public License as published by the Free +; Software Foundation; either version 2 of the License, or (at your option) +; any later version. +; +; This program is distributed in the hope that it will be useful, but WITHOUT +; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +; FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +; more details. + +[info] +name = cloud +version = 0.1.0-dev +longname = Cloud +author = "Thomas Vincent (somethingwithproof)" +email = thomasvincent@gmail.com +homepage = https://github.com/somethingwithproof/plugin_cloud +compat = 1.2.31 +capabilities = online_view:1, online_mgmt:1, offline_view:0, offline_mgmt:0, remote_collect:1 diff --git a/README.md b/README.md index 7961c6e..e94c2a6 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ A proposed Cacti 1.2 plugin that brings resources and metrics from public cloud providers into Cacti as ordinary devices, data sources, and graphs. Cloud workloads then sit next to the network that carries them, under Cacti's permissions, and Thold and Maint can alert on and suppress them. One plugin covers every provider, with a driver per provider: DigitalOcean, AWS, Google Cloud, and Azure first. -> **Status: proposal.** This repository contains no plugin code yet. It holds the design, its decision records, and the requirements tracked as issues and milestones. Nothing below describes shipped behavior. +> **Status: milestone 2 (foundation).** The plugin installs, stores accounts and credentials, and runs its collector, but no provider driver ships yet, so it collects nothing. DigitalOcean arrives in milestone 3. Do not run it in production. ## Why @@ -21,19 +21,48 @@ The plugin reads each provider's monitoring API on a Cacti poller, caches the la - **Cost before collection.** The plugin reads only metrics that have a Cacti data source, shows the expected request count and list-price cost before graphs are created, and enforces a monthly ceiling. ([ADR 0005](docs/decisions/0005-collect-only-what-is-graphed.md)) - **No plaintext credentials in the database.** Credentials come from an encrypted vault keyed by a file outside the database, from a credential file, or from the provider's instance identity. ([ADR 0007](docs/decisions/0007-credentials-outside-the-database-in-the-clear.md)) -## Planned scope +## Scope and status -| Phase | Scope | Milestones | -|---|---|---| -| 0, research | Provider fact confirmation, metric catalogs, cost and rate model, signing test vectors, transport spike | [M1](https://github.com/somethingwithproof/plugin_cloud/milestone/1) | -| 1, core and DigitalOcean | Accounts, credential vault, transport, collector, observation cache, Cacti objects, health page, DigitalOcean Droplets and load balancers | [M2](https://github.com/somethingwithproof/plugin_cloud/milestone/2), [M3](https://github.com/somethingwithproof/plugin_cloud/milestone/3), [M4](https://github.com/somethingwithproof/plugin_cloud/milestone/4) | -| 2, AWS | Signature Version 4, `AssumeRole`, instance roles, CloudWatch `GetMetricData`, regional inventory | [M5](https://github.com/somethingwithproof/plugin_cloud/milestone/5) | -| 3, Google Cloud | Service account JWT, metadata server, Cloud Monitoring `timeSeries.list` | [M6](https://github.com/somethingwithproof/plugin_cloud/milestone/6) | -| 4, Azure | Entra client credentials, managed identity, Resource Graph, `metrics:getBatch` | [M7](https://github.com/somethingwithproof/plugin_cloud/milestone/7) | -| 5, remote collectors | Accounts on Cacti remote data collectors | [M8](https://github.com/somethingwithproof/plugin_cloud/milestone/8) | +| Phase | Scope | Milestones | Status | +|---|---|---|---| +| 0, research | Provider fact confirmation, metric catalogs, cost and rate model, signing test vectors, transport spike | [M1](https://github.com/somethingwithproof/plugin_cloud/milestone/1) | Done, except the checks that need a live provider account | +| 1, core and DigitalOcean | Accounts, credential vault, transport, collector, observation cache, Cacti objects, health page, DigitalOcean Droplets and load balancers | [M2](https://github.com/somethingwithproof/plugin_cloud/milestone/2), [M3](https://github.com/somethingwithproof/plugin_cloud/milestone/3), [M4](https://github.com/somethingwithproof/plugin_cloud/milestone/4) | M2 in review ([#81](https://github.com/somethingwithproof/plugin_cloud/pull/81)); M3 and M4 not started | +| 2, AWS | Signature Version 4, `AssumeRole`, instance roles, CloudWatch `GetMetricData`, regional inventory | [M5](https://github.com/somethingwithproof/plugin_cloud/milestone/5) | Not started | +| 3, Google Cloud | Service account JWT, metadata server, Cloud Monitoring `timeSeries.list` | [M6](https://github.com/somethingwithproof/plugin_cloud/milestone/6) | Not started | +| 4, Azure | Entra client credentials, managed identity, Resource Graph, `metrics:getBatch` | [M7](https://github.com/somethingwithproof/plugin_cloud/milestone/7) | Not started | +| 5, remote collectors | Accounts on Cacti remote data collectors | [M8](https://github.com/somethingwithproof/plugin_cloud/milestone/8) | Not started | Out of scope: changing cloud resources, creating or mirroring provider alarms, billing reports, logs and traces, and a plugin-owned alerting engine. Further providers (Hetzner Cloud, Akamai Cloud, Oracle Cloud, and others) are research issues. +## What milestone 2 ships + +- **A guarded install.** On PHP below 8.2, or without ext-openssl, install and enable are refused with a message, and the rest of Cacti keeps working. +- **Lifecycle.** Install, upgrade, and uninstall through Cacti's Plugins page. Upgrades are ordered and survive interruption. Uninstall keeps the plugin's tables unless you clear *Keep Plugin Tables on Uninstall*. +- **Two realms.** *Cloud Admin* opens **Cloud Accounts**; *Cloud View* opens **Cloud Health**. Both pages are under Management. +- **Accounts and credentials.** Add, edit, verify, and delete accounts. A credential is either encrypted in the database with a key file kept outside it (AES-256-GCM), or read from a file on the poller. Credentials are write-only in the UI and are redacted from logs. +- **The collector.** It starts from each poller run, one instance per poller, within a time budget. It takes a lease per account, runs discovery on its own interval, and reads metrics only for the plugin's own active data sources. +- **Health.** Per-account collection, discovery, resource, and freshness state, plus warnings for an unusable vault key, unsafe credential files, and intervals the poller cannot honour. + +## Install and configure + +These steps install the milestone 2 code for evaluation. They require Cacti 1.2.31 or later on PHP 8.2 or later. + +1. Copy the repository to `plugins/cloud` under your Cacti directory. The directory must be named `cloud`. +2. Create the vault key outside the web root. Put it in a directory that only root and the Cacti user can write, and make the file readable only by the user that runs the web server and the poller. The plugin never creates or writes this file: + + ```sh + sudo install -d -m 0750 -o root -g cacti /etc/cacti + head -c 32 /dev/urandom | sudo tee /etc/cacti/cloud-vault.key > /dev/null + sudo chown cacti:cacti /etc/cacti/cloud-vault.key + sudo chmod 0600 /etc/cacti/cloud-vault.key + ``` + + Replace `cacti` with the user that runs your web server and poller. The file holds 32 raw bytes or 64 hexadecimal characters. Back it up with the database; without it, stored credentials must be entered again. +3. In Cacti, open **Configuration > Plugins**, then install and enable *Cloud*. +4. Under **Configuration > Settings > Cloud**, set *Vault Key File* if you used another path. *Collector Time Budget* (default 240 seconds) must stay below the poller interval. +5. Grant *Cloud Admin* or *Cloud View* to users and groups under **Configuration > Users**. Installing grants both realms to the administrator. +6. Add accounts under **Management > Cloud Accounts**, then check **Management > Cloud Health** for warnings. + ## Compatibility targets | Component | Target | @@ -66,6 +95,10 @@ flowchart LR - **Labels** also carry `area:`, `provider:`, `phase:`, `priority:`, and `status:`. See [CONTRIBUTING.md](CONTRIBUTING.md#labels). - The [project board](https://github.com/users/somethingwithproof/projects/7) shows all issues across milestones. +## Development + +CI lints the entry points on PHP 8.0, runs unit and integration tests and PHPStan level 9, and installs the plugin on PHP 8.2 to 8.5 against Cacti 1.2.31 and the 1.2.x branch. It also checks that PHP 8.1 is refused without breaking Cacti. The tests use Pest from Cacti core's plugin harness. That choice is provisional until [#12](https://github.com/somethingwithproof/plugin_cloud/issues/12) is decided. [.github/workflows/plugin-ci-workflow.yml](.github/workflows/plugin-ci-workflow.yml) lists every step. Run `sh tests/lint-workflows.sh` and `sh locales/build_gettext.sh --check` locally before pushing. + ## Contributing Read [CONTRIBUTING.md](CONTRIBUTING.md). Commits need a DCO sign-off. Design discussion happens on issues; open decisions carry the `type: decision` label. diff --git a/REUSE.toml b/REUSE.toml index f15b02a..17da5e5 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -1,7 +1,8 @@ version = 1 # Files that cannot carry a comment header, or whose format makes one -# awkward: documentation, repository metadata, and GitHub templates. +# awkward: documentation, repository metadata, GitHub templates, test +# configuration, and translation catalogs, which gettext regenerates. [[annotations]] path = [ "README.md", @@ -12,6 +13,10 @@ path = [ ".editorconfig", ".gitattributes", "REUSE.toml", + "phpunit.xml", + "phpunit-integration.xml", + "locales/po/**", + "locales/LC_MESSAGES/**", ] precedence = "aggregate" SPDX-FileCopyrightText = "2026 Thomas Vincent " diff --git a/cloud_accounts.php b/cloud_accounts.php new file mode 100644 index 0000000..1664efb --- /dev/null +++ b/cloud_accounts.php @@ -0,0 +1,128 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Cloud Accounts (Cloud Admin realm). This file must parse on PHP 8.0: Cacti + * may include it on an unsupported runtime, and cloud_page_start() refuses + * there before any plugin class loads. + */ + +chdir('../../'); +include('./include/auth.php'); +include_once('./plugins/cloud/setup.php'); + +if (!cloud_page_start()) { + exit; +} + +cloud_require_post('cloud_accounts.php', array('save', 'delete', 'verify')); + +$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_action = (string) get_nfilter_request_var('action'); + +switch ($cloud_action) { + case 'save': + $cloud_id = (int) get_filter_request_var('id'); + $cloud_input = array(); + + foreach (array('provider', 'name', 'poller_id', 'credential_source', 'credential_file', 'collect_interval', 'discover_interval', 'request_share', 'monthly_ceiling', 'enabled', 'scope_account_id', 'scope_regions', 'scope_project', 'scope_tenant', 'scope_subscription') as $cloud_field) { + $cloud_input[$cloud_field] = (string) get_nfilter_request_var($cloud_field); + } + + $cloud_existing = $cloud_id > 0 ? $cloud_accounts->find($cloud_id) : null; + + if ($cloud_id > 0 && $cloud_existing === null) { + header('Location: cloud_accounts.php'); + exit; + } + + // An existing account keeps its provider; only new ones choose. + if ($cloud_existing !== null) { + $cloud_input['provider'] = $cloud_existing->provider->value; + } + + $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)) { + $cloud_errors['name'] = __('Name: another account already uses this name.', 'cloud'); + } + + if ($cloud_errors !== array() || $cloud_parsed->account === null) { + top_header(); + $cloud_page->renderEdit($cloud_existing, $cloud_input, $cloud_errors); + bottom_footer(); + exit; + } + + $cloud_saved = $cloud_accounts->save($cloud_parsed->account, $cloud_user); + $cloud_raw = trim((string) get_nfilter_request_var('credential')); + + if ($cloud_saved > 0 && $cloud_raw !== '') { + try { + $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); + } + } + + unset($cloud_raw); + + if ($cloud_saved > 0) { + raise_message('cloud_saved', __('The account was saved.', 'cloud'), MESSAGE_LEVEL_INFO); + } else { + raise_message('cloud_saved', __('The account could not be saved.', 'cloud'), MESSAGE_LEVEL_ERROR); + } + + header('Location: cloud_accounts.php'); + 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); + } + + header('Location: cloud_accounts.php'); + exit; + case 'verify': + $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); + } + + header('Location: cloud_accounts.php'); + exit; + case 'edit': + $cloud_id = (int) get_filter_request_var('id'); + + top_header(); + $cloud_page->renderEdit($cloud_id > 0 ? $cloud_accounts->find($cloud_id) : null); + bottom_footer(); + exit; + default: + top_header(); + $cloud_page->renderList(); + bottom_footer(); +} diff --git a/cloud_health.php b/cloud_health.php new file mode 100644 index 0000000..65c24fb --- /dev/null +++ b/cloud_health.php @@ -0,0 +1,46 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Cloud Health (Cloud View realm). Parses on PHP 8.0; cloud_page_start() + * refuses an unsupported runtime before any plugin class loads. + */ + +chdir('../../'); +include('./include/auth.php'); +include_once('./plugins/cloud/setup.php'); + +if (!cloud_page_start()) { + exit; +} + +$cloud_clock = new \Somethingwithproof\Cloud\SystemClock(); +$cloud_page = new \Somethingwithproof\Cloud\HealthPage( + cloud_accounts(), + new \Somethingwithproof\Cloud\HealthRepository(false), + new \Somethingwithproof\Cloud\ResourceRepository(false, $cloud_clock), + new \Somethingwithproof\Cloud\ObservationRepository(false), + new \Somethingwithproof\Cloud\FreshnessEvaluator($cloud_clock), + \Somethingwithproof\Cloud\HealthWarnings::production(), + $cloud_clock +); + +top_header(); +$cloud_page->render(cloud_settings(), api_user_realm_auth('cloud_accounts.php'), (int) read_config_option('poller_interval')); +bottom_footer(); diff --git a/include/autoload.php b/include/autoload.php new file mode 100644 index 0000000..5a928bb --- /dev/null +++ b/include/autoload.php @@ -0,0 +1,45 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Class loader for lib/. Required only by cloud_boot() after the PHP version + * check, so class files may use PHP 8.2 syntax. This file itself stays PHP 8.0 + * compatible because it sits on the include path of setup.php. + */ + +spl_autoload_register(function ($class) { + $prefix = 'Somethingwithproof\\Cloud\\'; + + if (strncmp($class, $prefix, strlen($prefix)) !== 0) { + return; + } + + $name = substr($class, strlen($prefix)); + + // One flat directory: a namespace separator in the remainder is never ours. + if (strpos($name, '\\') !== false) { + return; + } + + $file = dirname(__DIR__) . '/lib/' . $name . '.php'; + + if (is_file($file)) { + require_once($file); + } +}); diff --git a/include/unbooted-uninstall.php b/include/unbooted-uninstall.php new file mode 100644 index 0000000..0fef0fb --- /dev/null +++ b/include/unbooted-uninstall.php @@ -0,0 +1,39 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Uninstall on a runtime the plugin refuses (PHP below 8.2, or a missing + * extension), where nothing under lib/ may load. Cacti goes on to drop every + * tracked plugin table after plugin_cloud_uninstall() returns, so the keep + * tables setting must be honoured here too, in PHP 8.0 syntax. It mirrors + * Settings::fromRow() and Schema::untrackTables() / forgetVersion(); the + * lifecycle integration tests run both paths. + */ + +function cloud_uninstall_unbooted(): void { + $row = db_fetch_row_prepared('SELECT value FROM settings WHERE name = ?', array('cloud_uninstall_keep_tables')); + $keep = !is_array($row) || $row === array() || (isset($row['value']) && $row['value'] === 'on'); + + if ($keep) { + db_execute_prepared("DELETE FROM plugin_db_changes WHERE plugin = ? AND method = 'create'", array('cloud')); + cacti_log('NOTE: Uninstall kept the plugin tables as configured', false, 'CLOUD'); + } else { + db_execute_prepared('DELETE FROM settings WHERE name = ?', array('cloud_schema_version')); + } +} diff --git a/index.php b/index.php new file mode 100644 index 0000000..d4377e6 --- /dev/null +++ b/index.php @@ -0,0 +1,20 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +header('Location: ../index.php'); diff --git a/lib/Account.php b/lib/Account.php new file mode 100644 index 0000000..038eb06 --- /dev/null +++ b/lib/Account.php @@ -0,0 +1,148 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * One cloud provider account (REQ-ACCT-001). Holds no secret: a vault + * credential lives in plugin_cloud_secret, a file credential on the poller. + */ +final readonly class Account { + public const MAIN_POLLER = 1; + + /** + * @param array $scope validated scope fields, see Provider::scopeFields() + */ + public function __construct( + public int $id, + public Provider $provider, + public string $name, + public int $pollerId, + public array $scope, + public CredentialSource $credentialSource, + public string $credentialFile, + public int $collectInterval, + public int $discoverInterval, + public int $requestShare, + public ?float $monthlyCeiling, + public AdminState $adminState, + public VerifyStatus $verifyStatus = VerifyStatus::Never, + public int $verifiedAt = 0, + ) { + } + + /** + * A row of plugin_cloud_account, or null when the row cannot be an account: + * no id, or a provider or credential source this code does not know. + * Every other loose value falls back to its documented default, pinned by + * tests/Unit/AccountTest.php. + * + * @param array $row + */ + public static function fromRow(array $row): ?self { + $id = Row::int($row, 'id', 0, 1); + $provider = Provider::tryFrom(Row::string($row, 'provider')); + $source = CredentialSource::tryFrom(Row::string($row, 'credential_source')); + + if ($id === 0 || $provider === null || $source === null) { + return null; + } + + $ceiling = Row::float($row, 'monthly_ceiling'); + + return new self( + id: $id, + provider: $provider, + name: Row::string($row, 'name'), + pollerId: Row::int($row, 'poller_id', self::MAIN_POLLER, 1), + scope: self::decodeScope(Row::string($row, 'scope'), $provider), + credentialSource: $source, + credentialFile: Row::string($row, 'credential_file'), + collectInterval: Row::int($row, 'collect_interval', AccountInput::DEFAULT_COLLECT, AccountInput::MIN_COLLECT), + discoverInterval: Row::int($row, 'discover_interval', AccountInput::DEFAULT_DISCOVER, AccountInput::MIN_DISCOVER), + requestShare: min(Row::int($row, 'request_share', AccountInput::DEFAULT_SHARE, 1), 100), + monthlyCeiling: $ceiling !== null && $ceiling >= 0 ? $ceiling : null, + adminState: AdminState::tryFrom(Row::string($row, 'admin_state')) ?? AdminState::Disabled, + verifyStatus: VerifyStatus::tryFrom(Row::string($row, 'verify_status')) ?? VerifyStatus::Never, + verifiedAt: Row::int($row, 'verified_at', 0, 0), + ); + } + + /** + * Only the provider's own scope fields survive, and only values that still + * match their pattern, so a hand-edited row cannot put text into a URL. + * + * @return array + */ + private static function decodeScope(string $json, Provider $provider): array { + $decoded = json_decode($json, true, 4); + $scope = []; + + if (!is_array($decoded)) { + return []; + } + + foreach ($provider->scopeFields() as $field => $rule) { + $value = $decoded[$field] ?? null; + + if (is_string($value) && AccountInput::scopeValueValid($value, $rule)) { + $scope[$field] = $value; + } + } + + return $scope; + } + + /** + * Column values for plugin_cloud_account, without id and timestamps. + * + * @return array + */ + public function toRow(): array { + return [ + 'provider' => $this->provider->value, + 'name' => $this->name, + 'poller_id' => $this->pollerId, + 'scope' => (string) json_encode((object) $this->scope), + 'credential_source' => $this->credentialSource->value, + 'credential_file' => $this->credentialFile, + 'collect_interval' => $this->collectInterval, + 'discover_interval' => $this->discoverInterval, + 'request_share' => $this->requestShare, + 'monthly_ceiling' => $this->monthlyCeiling, + 'admin_state' => $this->adminState->value, + ]; + } + + /** + * Names of the columns that differ from $before, for the audit log. + * + * @return list + */ + 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)); + } + + public function enabled(): bool { + return $this->adminState === AdminState::Enabled; + } +} diff --git a/lib/AccountHealth.php b/lib/AccountHealth.php new file mode 100644 index 0000000..7e8c844 --- /dev/null +++ b/lib/AccountHealth.php @@ -0,0 +1,68 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * The last collector and discovery result for one account, as stored in + * plugin_cloud_health. + */ +final readonly class AccountHealth { + public function __construct( + public int $accountId, + public int $runStarted = 0, + public int $runFinished = 0, + public float $runDuration = 0.0, + public CollectionState $collection = CollectionState::Never, + public ?ErrorClass $error = null, + public int $requests = 0, + public int $seriesTotal = 0, + public int $seriesRead = 0, + public int $discoveredAt = 0, + public CollectionState $discovery = CollectionState::Never, + ) { + } + + /** + * @param array $row + */ + public static function fromRow(array $row): ?self { + $id = Row::int($row, 'account_id', 0, 1); + + if ($id === 0) { + return null; + } + + $error = Row::string($row, 'error_class'); + + return new self( + accountId: $id, + runStarted: Row::int($row, 'run_started', 0, 0), + runFinished: Row::int($row, 'run_finished', 0, 0), + runDuration: max(0.0, Row::float($row, 'run_duration') ?? 0.0), + collection: CollectionState::tryFrom(Row::string($row, 'collection')) ?? CollectionState::Never, + error: $error === '' ? null : ErrorClass::tryFrom($error), + requests: Row::int($row, 'requests', 0, 0), + seriesTotal: Row::int($row, 'series_total', 0, 0), + seriesRead: Row::int($row, 'series_read', 0, 0), + discoveredAt: Row::int($row, 'discovered_at', 0, 0), + discovery: CollectionState::tryFrom(Row::string($row, 'discovery')) ?? CollectionState::Never, + ); + } +} diff --git a/lib/AccountInput.php b/lib/AccountInput.php new file mode 100644 index 0000000..cbc4b68 --- /dev/null +++ b/lib/AccountInput.php @@ -0,0 +1,162 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * Validation of the account form. The result is either an Account or a + * message per field, each naming the field it is about. + */ +final readonly class AccountInput { + public const MIN_COLLECT = 60; + public const DEFAULT_COLLECT = 300; + public const MIN_DISCOVER = 300; + public const DEFAULT_DISCOVER = 3600; + public const DEFAULT_SHARE = 50; + public const MAX_INTERVAL = 86400; + + /** + * @param array $errors field => message + */ + private function __construct(public ?Account $account, public array $errors) { + } + + /** + * @param array $input form fields as posted + * @param list $offered providers new accounts may use + */ + public static function parse(array $input, int $id, array $offered): self { + $errors = []; + $provider = Provider::tryFrom(Row::string($input, 'provider')); + + if ($provider === null || ($id <= 0 && !in_array($provider, $offered, true))) { + return new self(null, ['provider' => __('Provider: choose one of the listed providers.', 'cloud')]); + } + + $name = Row::string($input, 'name'); + + if ($name === '' || mb_strlen($name) > 100 || preg_match('/[\x00-\x1f\x7f]/', $name) === 1) { + $errors['name'] = __('Name: enter 1 to 100 characters without control characters.', 'cloud'); + } + + // Phase 1 collects only on the main poller (REQ-ACCT-003). + $poller = Row::int($input, 'poller_id', 0); + + if ($poller !== Account::MAIN_POLLER) { + $errors['poller_id'] = __('Poller: only the main poller can collect cloud accounts in this release.', 'cloud'); + } + + $scope = []; + + foreach ($provider->scopeFields() as $field => $rule) { + $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'); + } else { + $scope[$field] = $value; + } + } + + $source = CredentialSource::tryFrom(Row::string($input, 'credential_source')); + + if ($source === null || !in_array($source, $provider->credentialSources(), true)) { + $errors['credential_source'] = __('Credential Source: choose one this provider supports.', 'cloud'); + } + + $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'); + } + + $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'); + } + + 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'); + } + $share = Row::int($input, 'request_share', 0); + + if ($share < 1 || $share > 100) { + $errors['request_share'] = __('Request Share: enter a whole percentage from 1 to 100.', 'cloud'); + } + + $ceiling = null; + + if (Row::string($input, 'monthly_ceiling') !== '') { + $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'); + } + } + + if ($errors !== [] || $source === null) { + return new self(null, $errors); + } + + return new self(new Account( + id: $id, + provider: $provider, + name: $name, + pollerId: $poller, + scope: $scope, + credentialSource: $source, + credentialFile: $source === CredentialSource::File ? $file : '', + collectInterval: $collect, + discoverInterval: $discover, + requestShare: $share, + monthlyCeiling: $ceiling, + adminState: Row::bool($input, 'enabled') ? AdminState::Enabled : AdminState::Disabled, + ), []); + } + + /** + * @param array{pattern: string, list: bool} $rule + */ + public static function scopeValueValid(string $value, array $rule): bool { + if ($value === '' || strlen($value) > 512) { + return false; + } + + foreach ($rule['list'] ? explode(',', $value) : [$value] as $part) { + if (preg_match($rule['pattern'], $part) !== 1) { + return false; + } + } + + return true; + } + + public static function scopeLabel(string $field): string { + return match ($field) { + 'account_id' => __('AWS Account ID', 'cloud'), + 'regions' => __('Regions', 'cloud'), + 'project' => __('Project ID', 'cloud'), + 'tenant' => __('Tenant ID', 'cloud'), + 'subscription' => __('Subscription ID', 'cloud'), + default => $field, + }; + } +} diff --git a/lib/AccountRepository.php b/lib/AccountRepository.php new file mode 100644 index 0000000..93221a9 --- /dev/null +++ b/lib/AccountRepository.php @@ -0,0 +1,213 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * Accounts and their audit log. Every change writes an audit row naming the + * user, the time, and the changed columns, never their values, so no secret + * or credential path history accumulates there (REQ-ACCT-005). + */ +final class AccountRepository { + public function __construct(private readonly \PDO|false $connection, private readonly Clock $clock) { + } + + public function find(int $id): ?Account { + $row = db_fetch_row_prepared('SELECT * FROM plugin_cloud_account WHERE id = ?', [$id], true, $this->connection); + + return is_array($row) ? Account::fromRow($row) : null; + } + + /** + * @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))); + } + + /** + * Enabled accounts owned by one poller, for that poller's collector. + * + * @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))); + } + + 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; + } + + /** + * Insert or update, returning the account id, or 0 when the write failed. + */ + public function save(Account $account, int $userId): int { + $before = $account->id > 0 ? $this->find($account->id) : null; + $row = $account->toRow(); + $now = $this->clock->now(); + + if ($account->id > 0 && $before === null) { + return 0; + } + + 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); + $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); + $id = $ok ? $account->id : 0; + $action = 'update'; + } + + $changed = $account->changedFields($before); + + if ($id > 0 && $changed !== []) { + $this->audit($id, $userId, $action, $changed); + } + + return $id; + } + + private const DELETE_ATTEMPTS = 3; + + /** + * Remove the account and everything collected for it. Its Cacti devices + * and graphs are left to the administrator. + */ + public function delete(int $id, int $userId): bool { + if ($this->find($id) === null) { + return false; + } + + // All or nothing: an account must not lose its credential or data + // while its row stays. InnoDB rolls back the whole transaction on a + // deadlock, and Cacti then retries the failed statement on its own, + // outside any transaction. So the transaction is checked after every + // statement, and if it has ended the whole delete runs again. Every + // statement is idempotent, and the account row goes last, so an + // interrupted attempt leaves an account that can be deleted again. + $statements = [ + ['DELETE FROM plugin_cloud_secret WHERE account_id = ?', [$id]], + ['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 FROM plugin_cloud_resource WHERE account_id = ?', [$id]], + ['DELETE FROM plugin_cloud_account WHERE id = ?', [$id]], + ]; + + for ($attempt = 0; $attempt < self::DELETE_ATTEMPTS; $attempt++) { + if (!db_begin_transaction($this->connection)) { + return false; + } + + $intact = true; + + foreach ($statements as [$sql, $params]) { + if (!db_execute_prepared($sql, $params, true, $this->connection) || !$this->inTransaction()) { + $intact = false; + + break; + } + } + + if ($intact && db_commit_transaction($this->connection)) { + $this->audit($id, $userId, 'delete', []); + + return true; + } + + if ($this->inTransaction()) { + db_rollback_transaction($this->connection); + } + } + + return false; + } + + 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); + + $this->audit($id, $userId, 'verify', ['verify_status']); + } + + /** + * A credential replacement is an account change too; only the fact is logged. + */ + public function recordCredentialChange(int $id, int $userId): void { + $this->audit($id, $userId, 'credential', ['credential']); + } + + /** + * @return list}> + */ + 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) { + $fields = Row::string($row, 'fields'); + + $entries[] = [ + 'account_id' => Row::int($row, 'account_id'), + 'user_id' => Row::int($row, 'user_id'), + 'changed_at' => Row::int($row, 'changed_at'), + 'action' => Row::string($row, 'action'), + 'fields' => $fields === '' ? [] : explode(',', $fields), + ]; + } + + return $entries; + } + + private function inTransaction(): bool { + return (int) db_fetch_cell_prepared('SELECT @@in_transaction', [], '', true, $this->connection) === 1; + } + + /** + * @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); + } + + /** + * @param list> $rows + * @return list + */ + private function accounts(array $rows): array { + $accounts = []; + + foreach ($rows as $row) { + $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'))); + + continue; + } + + $accounts[] = $account; + } + + return $accounts; + } +} diff --git a/lib/AccountsPage.php b/lib/AccountsPage.php new file mode 100644 index 0000000..37975b6 --- /dev/null +++ b/lib/AccountsPage.php @@ -0,0 +1,149 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * The Cloud Accounts page. Every provider or user string is escaped where + * it is printed; no stored credential is ever printed, only whether one is + * stored (REQ-CRED-004). Every action that changes state is a POST form, and + * csrf-magic adds its token to each. + */ +final class AccountsPage { + public const FILE = 'cloud_accounts.php'; + + public function __construct( + private readonly AccountRepository $accounts, + private readonly CredentialStore $credentials, + ) { + } + + 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'), + ])) . ''; + + $accounts = $this->accounts->all(); + + if ($accounts === []) { + print '' . html_escape(__('No cloud accounts yet.', 'cloud')) . ''; + } + + foreach ($accounts as $account) { + print '' + . '' . 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_end_box(); + } + + /** + * @param array $input the rejected form values, to show again + * @param array $errors field => message + */ + public function renderEdit(?Account $account, array $input = [], array $errors = []): void { + $value = static function (string $field, string $current) use ($input): string { + return array_key_exists($field, $input) ? Row::string($input, $field) : $current; + }; + + $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', ''); + + 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->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); + } + + $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); + + // 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')) . '' + . ''; + + $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')) . ''; + + html_end_box(); + + print '' + . '' + . '' + . '' + . '
'; + } + + 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::File => __('File on the poller', 'cloud'), + CredentialSource::Instance => __('Instance identity', 'cloud'), + }; + } + + private function actionForm(int $id, string $action, string $label): string { + return '
' + . '' + . '' + . '' + . '
'; + } + + 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 ''; + } +} diff --git a/lib/AdminState.php b/lib/AdminState.php new file mode 100644 index 0000000..567ea5f --- /dev/null +++ b/lib/AdminState.php @@ -0,0 +1,25 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +enum AdminState: string { + case Enabled = 'enabled'; + case Disabled = 'disabled'; +} diff --git a/lib/Clock.php b/lib/Clock.php new file mode 100644 index 0000000..96ceab9 --- /dev/null +++ b/lib/Clock.php @@ -0,0 +1,24 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +interface Clock { + public function now(): int; +} diff --git a/lib/CloudResource.php b/lib/CloudResource.php new file mode 100644 index 0000000..3c458ab --- /dev/null +++ b/lib/CloudResource.php @@ -0,0 +1,56 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * A resource as discovery reports it. Provider strings are untrusted and + * escaped wherever they are printed. The type and provider id are its + * identity, so a value that does not fit its column, or holds control + * characters, is refused rather than altered: two resources must never be + * made to share one row. Display fields are trimmed to fit. + */ +final readonly class CloudResource { + public string $type; + public string $providerId; + public string $name; + public string $region; + + public function __construct(string $type, string $providerId, string $name, string $region = '') { + $this->type = self::identity($type, 64, 'type'); + $this->providerId = self::identity($providerId, 255, 'provider id'); + $this->name = self::bounded($name, 255); + $this->region = self::bounded($region, 64); + } + + /** + * @throws DriverError + */ + 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'); + } + + return $value; + } + + private static function bounded(string $value, int $length): string { + return mb_substr((string) preg_replace('/[\x00-\x1f\x7f]/', '', $value), 0, $length); + } +} diff --git a/lib/CollectResult.php b/lib/CollectResult.php new file mode 100644 index 0000000..1168cfc --- /dev/null +++ b/lib/CollectResult.php @@ -0,0 +1,32 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +final readonly class CollectResult { + /** + * @param list $observations + */ + public function __construct( + public array $observations, + public int $requests, + public ?ErrorClass $error = null, + ) { + } +} diff --git a/lib/CollectionState.php b/lib/CollectionState.php new file mode 100644 index 0000000..893b64a --- /dev/null +++ b/lib/CollectionState.php @@ -0,0 +1,29 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +enum CollectionState: string { + case Never = 'never'; + case Ok = 'ok'; + case Partial = 'partial'; + case Failed = 'failed'; + case Budget = 'budget'; + case NotDue = 'not_due'; +} diff --git a/lib/Collector.php b/lib/Collector.php new file mode 100644 index 0000000..d0ea23f --- /dev/null +++ b/lib/Collector.php @@ -0,0 +1,180 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * One collector run on one poller (REQ-COLL-001 to REQ-COLL-006). + * + * It handles only enabled accounts owned by its poller, stops starting new + * accounts once its time budget is spent, holds a lease for each account it + * works on, runs discovery only when that is due and never reads metrics + * there, and reads metrics only for the plugin's active data sources. An + * interrupted run leaves every account either untouched or fully written for + * the work it finished, and the next run continues. + */ +final class Collector { + public const DUE_SLACK = 30; + + /** + * Seconds after a run's start when the account is due again: its + * interval less a slack of a tenth of it, at most DUE_SLACK. + */ + public static function dueAfter(int $collectInterval): int { + return $collectInterval - min(self::DUE_SLACK, intdiv($collectInterval, 10)); + } + + public function __construct( + private readonly AccountRepository $accounts, + private readonly Drivers $drivers, + private readonly CredentialStore $credentials, + private readonly LeaseRepository $leases, + private readonly ResourceRepository $resources, + private readonly SeriesRepository $series, + private readonly ObservationRepository $observations, + private readonly HealthRepository $health, + private readonly Redactor $redactor, + private readonly Clock $clock, + private readonly string $holder, + ) { + } + + /** + * @return array{accounts: int, skipped: int, stopped_early: bool} + */ + public function run(int $pollerId, int $budgetSeconds): array { + $started = $this->clock->now(); + $done = 0; + $skipped = 0; + + // Least recently attempted first, so an account that overruns the + // budget on every run cannot keep the ones after it from running. + // Attempts come from the lease, because an overrun can lose the lease + // and with it the health write that would have recorded the run. + $accounts = $this->accounts->enabledForPoller($pollerId); + $lastRun = []; + + foreach ($accounts as $account) { + $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]); + + foreach ($accounts as $account) { + if ($this->clock->now() - $started >= $budgetSeconds) { + Log::warning(sprintf('Collector budget of %d seconds spent; remaining accounts resume next run', $budgetSeconds)); + + return ['accounts' => $done, 'skipped' => $skipped, 'stopped_early' => true]; + } + + if (!$this->leases->acquire($account->id, $this->holder, $budgetSeconds + 60)) { + $skipped++; + + continue; + } + + try { + $this->runAccount($account); + $done++; + } finally { + $this->leases->release($account->id, $this->holder); + } + } + + return ['accounts' => $done, 'skipped' => $skipped, 'stopped_early' => false]; + } + + private function runAccount(Account $account): void { + $now = $this->clock->now(); + $start = microtime(true); + $previous = $this->health->find($account->id); + + // Each run starts a few seconds after its poller cycle, so the time + // since the last start drifts around the interval. Without slack, an + // interval equal to the poller interval would often read as not yet + // due and collect only every other cycle. + if ($previous->runStarted > 0 && $now - $previous->runStarted < self::dueAfter($account->collectInterval)) { + return; + } + + $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()); + + return; + } + + try { + $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()); + + return; + } + + $this->redactor->add($credential); + + $requests = 0; + $discoveredAt = $previous->discoveredAt; + $discovery = $previous->discovery; + + if ($now - $previous->discoveredAt >= $account->discoverInterval) { + try { + $inventory = $driver->discover($account, $credential); + $requests += $inventory->requests; + $discovery = $this->resources->sync($account->id, $inventory, $this->leases, $this->holder) ? CollectionState::Ok : CollectionState::Partial; + $discoveredAt = $now; + } catch (DriverError|TransportError $e) { + $discovery = CollectionState::Failed; + Log::warning(sprintf('Account %d: discovery failed: %s', $account->id, $this->redactor->clean($e->getMessage()))); + } + } + + $wanted = $this->series->enabledFor($account->id); + $result = $wanted === [] ? new CollectResult([], 0) : $driver->collect($account, $credential, $wanted); + $read = 0; + + foreach ($result->observations as $observation) { + $this->observations->write($account->id, $this->holder, $this->clock->now(), $observation); + $read++; + } + + $state = match (true) { + $result->error !== null && $read === 0 => CollectionState::Failed, + $result->error !== null || $read < count($wanted) => CollectionState::Partial, + default => CollectionState::Ok, + }; + + $this->health->save(new AccountHealth( + accountId: $account->id, + runStarted: $now, + runFinished: $this->clock->now(), + runDuration: microtime(true) - $start, + collection: $state, + error: $result->error, + requests: $requests + $result->requests, + seriesTotal: count($wanted), + seriesRead: $read, + discoveredAt: $discoveredAt, + discovery: $discovery, + ), $this->holder, $this->clock->now()); + } +} diff --git a/lib/CredentialError.php b/lib/CredentialError.php new file mode 100644 index 0000000..90c21b0 --- /dev/null +++ b/lib/CredentialError.php @@ -0,0 +1,31 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * A refused key or credential file, or an unreadable vault entry. The + * message is fixed text naming the check that failed; it never holds file + * contents or secret material. + */ +final class CredentialError extends \RuntimeException { + public static function because(string $reason): self { + return new self($reason); + } +} diff --git a/lib/CredentialFile.php b/lib/CredentialFile.php new file mode 100644 index 0000000..b0f98bf --- /dev/null +++ b/lib/CredentialFile.php @@ -0,0 +1,44 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * A credential stored in a file on the poller instead of the vault. + */ +final class CredentialFile { + public const MAX_BYTES = 16384; + + public static function pathAcceptable(string $path): bool { + return SecureFile::pathAcceptable($path); + } + + /** + * @throws CredentialError + */ + public static function read(string $path): Secret { + $content = trim(SecureFile::read($path, self::MAX_BYTES)); + + if ($content === '') { + throw CredentialError::because('the credential file is empty'); + } + + return new Secret($content); + } +} diff --git a/lib/CredentialSource.php b/lib/CredentialSource.php new file mode 100644 index 0000000..b4df081 --- /dev/null +++ b/lib/CredentialSource.php @@ -0,0 +1,37 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * Where an account's credential comes from (ADR 0007). + */ +enum CredentialSource: string { + case Vault = 'vault'; + case File = 'file'; + case Instance = 'instance'; + + public function label(): string { + return match ($this) { + self::Vault => __('Stored in the plugin vault', 'cloud'), + self::File => __('Credential file on the poller', 'cloud'), + self::Instance => __('Instance identity of the poller', 'cloud'), + }; + } +} diff --git a/lib/CredentialStore.php b/lib/CredentialStore.php new file mode 100644 index 0000000..6a9d541 --- /dev/null +++ b/lib/CredentialStore.php @@ -0,0 +1,84 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * Resolves an account's credential from its source, and stores replacements + * in the vault. The vault key is loaded only when a vault value is used, so + * accounts with credential files work without a key file. + */ +final class CredentialStore { + private ?Vault $vault = null; + + public function __construct( + private readonly SecretRepository $secrets, + private readonly string $keyFile, + ) { + } + + /** + * @throws CredentialError + */ + public function credentialFor(Account $account): Secret { + return match ($account->credentialSource) { + CredentialSource::File => CredentialFile::read($account->credentialFile), + CredentialSource::Vault => $this->fromVault($account->id), + CredentialSource::Instance => throw CredentialError::because('instance identity is not available for this provider'), + }; + } + + public function hasVaultCredential(int $accountId): bool { + return $this->secrets->has($accountId, SecretRepository::CREDENTIAL); + } + + /** + * @throws CredentialError + */ + public function storeVaultCredential(int $accountId, Secret $secret): void { + if ($secret->isEmpty() || strlen($secret->reveal()) > CredentialFile::MAX_BYTES) { + throw CredentialError::because('the credential is empty or too long'); + } + + if (!$this->secrets->store($accountId, SecretRepository::CREDENTIAL, $this->vault()->encrypt($secret, $accountId, SecretRepository::CREDENTIAL))) { + throw CredentialError::because('the credential could not be stored'); + } + } + + public function forget(int $accountId): void { + $this->secrets->delete($accountId, SecretRepository::CREDENTIAL); + } + + /** + * @throws CredentialError + */ + private function fromVault(int $accountId): Secret { + $entry = $this->secrets->load($accountId, SecretRepository::CREDENTIAL); + + if ($entry === null) { + throw CredentialError::because('no credential is stored for this account'); + } + + return $this->vault()->decrypt($entry, $accountId, SecretRepository::CREDENTIAL); + } + + private function vault(): Vault { + return $this->vault ??= new Vault(VaultKey::fromFile($this->keyFile)); + } +} diff --git a/lib/DriverError.php b/lib/DriverError.php new file mode 100644 index 0000000..cfa5009 --- /dev/null +++ b/lib/DriverError.php @@ -0,0 +1,30 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +final class DriverError extends \RuntimeException { + public function __construct(public readonly ErrorClass $errorClass, string $reason = '') { + parent::__construct($errorClass->value . ($reason !== '' ? ': ' . $reason : '')); + } + + public static function fromTransport(TransportError $error): self { + return new self($error->errorClass(), $error->kind); + } +} diff --git a/lib/Drivers.php b/lib/Drivers.php new file mode 100644 index 0000000..1eb7505 --- /dev/null +++ b/lib/Drivers.php @@ -0,0 +1,64 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * Builds the driver for an account, wired to a transport that enforces the + * account's outbound policy and the driver's operation list. No provider has + * a driver yet: DigitalOcean's arrives with milestone 3, and until then an + * account reports a configuration status instead of collecting. + */ +final class Drivers { + /** + * @var array + */ + private array $factories = []; + + /** + * @param \Closure(OutboundPolicy): HttpTransport $transport + */ + public function __construct(private readonly \Closure $transport) { + } + + public static function production(): self { + return new self(static fn (OutboundPolicy $policy): HttpTransport => new SocketTransport($policy)); + } + + /** + * @param \Closure(HttpTransport): ProviderDriver $factory + */ + public function register(Provider $provider, \Closure $factory): void { + $this->factories[$provider->value] = $factory; + } + + public function for(Account $account): ?ProviderDriver { + $factory = $this->factories[$account->provider->value] ?? null; + + if ($factory === null) { + return null; + } + + // The driver is built twice: once unwired to learn its endpoints and + // operations, then with the guarded transport it will actually use. + $probe = $factory(new GuardedTransport(new RefusingTransport(), [])); + + return $factory(new GuardedTransport(($this->transport)($probe->endpoints($account)), $probe->operations())); + } +} diff --git a/lib/ErrorClass.php b/lib/ErrorClass.php new file mode 100644 index 0000000..4d6c916 --- /dev/null +++ b/lib/ErrorClass.php @@ -0,0 +1,33 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * Every failure a driver or the transport reports is reduced to one of these + * classes. Provider text never travels further than the driver. + */ +enum ErrorClass: string { + case Auth = 'auth'; + case Permission = 'permission'; + case Throttled = 'throttled'; + case Transient = 'transient'; + case Malformed = 'malformed'; + case Config = 'config'; +} diff --git a/lib/FixedClock.php b/lib/FixedClock.php new file mode 100644 index 0000000..b8a5f62 --- /dev/null +++ b/lib/FixedClock.php @@ -0,0 +1,36 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * A clock that stays where it is put, for tests and for replaying a run. + */ +final class FixedClock implements Clock { + public function __construct(private int $time) { + } + + public function now(): int { + return $this->time; + } + + public function advance(int $seconds): void { + $this->time += $seconds; + } +} diff --git a/lib/Freshness.php b/lib/Freshness.php new file mode 100644 index 0000000..b335c2f --- /dev/null +++ b/lib/Freshness.php @@ -0,0 +1,36 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +enum Freshness: string { + case Current = 'current'; + case Delayed = 'delayed'; + case Stale = 'stale'; + case Never = 'never'; + case ClockSkew = 'clock_skew'; + + /** + * Only a current or delayed value is served; everything else reads as + * unknown, never zero (REQ-STATE-004). + */ + public function usable(): bool { + return $this === self::Current || $this === self::Delayed; + } +} diff --git a/lib/FreshnessEvaluator.php b/lib/FreshnessEvaluator.php new file mode 100644 index 0000000..7434e03 --- /dev/null +++ b/lib/FreshnessEvaluator.php @@ -0,0 +1,57 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * Freshness of a datapoint from its provider timestamp (REQ-STATE-002). + * + * A value is current within the metric's period plus its publication delay + * plus the collection interval, delayed up to twice that, and stale beyond. + * A datapoint stamped in the future by more than the allowance means the + * poller's clock or the provider's disagrees, and the value is unknown with + * reason clock_skew (REQ-STATE-005). The fetch time never counts: a recent + * fetch of an old datapoint is still old. + */ +final class FreshnessEvaluator { + public const SKEW_ALLOWANCE = 120; + + public function __construct(private readonly Clock $clock) { + } + + public function evaluate(?Observation $observation, int $period, int $delay, int $collectInterval): Freshness { + if ($observation === null || $observation->observedAt <= 0) { + return Freshness::Never; + } + + $age = $this->clock->now() - $observation->observedAt; + + if ($age < -self::SKEW_ALLOWANCE) { + return Freshness::ClockSkew; + } + + $window = max(1, $period) + max(0, $delay) + max(1, $collectInterval); + + return match (true) { + $age <= $window => Freshness::Current, + $age <= 2 * $window => Freshness::Delayed, + default => Freshness::Stale, + }; + } +} diff --git a/lib/GuardedTransport.php b/lib/GuardedTransport.php new file mode 100644 index 0000000..2717291 --- /dev/null +++ b/lib/GuardedTransport.php @@ -0,0 +1,50 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * Refuses any request that is not one of the driver's listed operations + * before it reaches the network, and before a signer sees it. + */ +final class GuardedTransport implements HttpTransport { + /** + * @param list $operations + */ + public function __construct(private readonly HttpTransport $inner, private readonly array $operations) { + } + + public function allows(HttpRequest $request): ?Operation { + foreach ($this->operations as $operation) { + if ($operation->matches($request)) { + return $operation; + } + } + + return null; + } + + 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)); + } + + return $this->inner->send($request); + } +} diff --git a/lib/HealthPage.php b/lib/HealthPage.php new file mode 100644 index 0000000..56be937 --- /dev/null +++ b/lib/HealthPage.php @@ -0,0 +1,149 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * The Cloud Health page. It shows what the collectors last recorded and + * never calls a provider. Ages come from datapoint and run times, so a recent + * page load never looks like a recent measurement. + * + * Until the metric catalogs arrive with each driver, freshness uses the + * account's collection interval as the metric period and no publication + * delay. + */ +final class HealthPage { + public const FILE = 'cloud_health.php'; + + public function __construct( + private readonly AccountRepository $accounts, + private readonly HealthRepository $health, + private readonly ResourceRepository $resources, + private readonly ObservationRepository $observations, + private readonly FreshnessEvaluator $freshness, + private readonly HealthWarnings $warnings, + private readonly Clock $clock, + ) { + } + + /** + * @param bool $admin whether the viewer has Cloud Admin, which alone sees + * credential state and credential warnings + */ + public function render(Settings $settings, bool $admin, int $pollerInterval): void { + $accounts = $this->accounts->all(); + + html_start_box(__('Cloud Warnings', 'cloud'), '100%', '', '3', 'center', ''); + + $shown = 0; + + foreach ($this->warnings->for($settings, $accounts, $pollerInterval) as $warning) { + if ($warning['admin'] && !$admin) { + continue; + } + + print '' . html_escape($warning['message']) . ''; + $shown++; + } + + if ($shown === 0) { + print '' . html_escape(__('No warnings.', 'cloud')) . ''; + } + + html_end_box(); + + 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')]; + + if ($admin) { + array_splice($headers, 1, 0, [__('Credential', 'cloud')]); + } + + print '' . implode('', array_map('html_escape', $headers)) . ''; + + if ($accounts === []) { + print '' . html_escape(__('No cloud accounts yet.', 'cloud')) . ''; + } + + foreach ($accounts as $account) { + $row = $this->row($account); + + if ($admin) { + array_splice($row, 1, 0, [$account->verifyStatus->message()]); + } + + print '' . implode('', array_map('html_escape', $row)) . ''; + } + + html_end_box(); + } + + /** + * The cells of one account's row, as plain text. + * + * @return list + */ + public function row(Account $account): array { + $health = $this->health->find($account->id); + + $collection = $account->enabled() ? $this->collectionLabel($health) : __('Disabled', 'cloud'); + $counts = $this->resources->counts($account->id); + $freshness = []; + + foreach ($this->observations->forAccount($account->id) as $entry) { + $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, + default => $entry['status'], + }; + + $freshness[$state] = ($freshness[$state] ?? 0) + 1; + } + + ksort($freshness); + + return [ + $account->name, + $collection, + $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)), + ]; + } + + private function collectionLabel(AccountHealth $health): string { + return $health->error === null ? $health->collection->value : $health->collection->value . ' (' . $health->error->value . ')'; + } + + private function age(int $time): string { + $seconds = max(0, $this->clock->now() - $time); + + return match (true) { + $seconds < 120 => __('%d seconds ago', $seconds, 'cloud'), + $seconds < 7200 => __('%d minutes ago', intdiv($seconds, 60), 'cloud'), + $seconds < 172800 => __('%d hours ago', intdiv($seconds, 3600), 'cloud'), + default => __('%d days ago', intdiv($seconds, 86400), 'cloud'), + }; + } +} diff --git a/lib/HealthRepository.php b/lib/HealthRepository.php new file mode 100644 index 0000000..a5341d9 --- /dev/null +++ b/lib/HealthRepository.php @@ -0,0 +1,48 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +final class HealthRepository { + 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); + + return (is_array($row) ? AccountHealth::fromRow($row) : null) ?? new AccountHealth($accountId); + } + + /** + * Written only while $holder still holds the account's lease, checked in + * the same statement, so a run that lost its lease leaves the newer + * 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), + 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, $holder, $now, + ], true, $this->connection); + } +} diff --git a/lib/HealthWarnings.php b/lib/HealthWarnings.php new file mode 100644 index 0000000..ece4fb6 --- /dev/null +++ b/lib/HealthWarnings.php @@ -0,0 +1,110 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * The health page's warnings (REQ-HEALTH-002): a vault key file that is + * missing or refused, a credential file that fails its checks, and a + * collection interval the poller interval cannot honour. + * + * File checks run on the server rendering the page; a collector on another + * poller reads its own copies. Credential file warnings name an account's + * configuration, so they are for Cloud Admin only (REQ-HEALTH-004). + */ +final class HealthWarnings { + /** + * @param \Closure(string): void $keyCheck throws CredentialError for an unusable key file + * @param \Closure(string): void $fileCheck throws CredentialError for an unusable credential file + */ + public function __construct( + private readonly \Closure $keyCheck, + private readonly \Closure $fileCheck, + ) { + } + + public static function production(): self { + return new self( + static function (string $path): void { + VaultKey::fromFile($path); + }, + static function (string $path): void { + SecureFile::check($path, CredentialFile::MAX_BYTES); + }, + ); + } + + /** + * @param list $accounts + * + * @return list + */ + public function for(Settings $settings, array $accounts, int $pollerInterval): array { + $warnings = []; + + 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]; + } + + foreach ($accounts as $account) { + if (!$account->enabled()) { + continue; + } + + if ($account->credentialSource === CredentialSource::File) { + 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]; + } + } + + $interval = $this->intervalWarning($account, $pollerInterval); + + if ($interval !== null) { + $warnings[] = ['message' => $interval, 'admin' => false]; + } + } + + return $warnings; + } + + /** + * The collector runs once per poller cycle, so it collects an account + * at the first whole number of poller intervals that reaches the + * collector's due threshold for it (Collector::dueAfter()). + */ + private function intervalWarning(Account $account, int $pollerInterval): ?string { + if ($pollerInterval < 1) { + return null; + } + + $effective = max(1, (int) ceil(Collector::dueAfter($account->collectInterval) / $pollerInterval)) * $pollerInterval; + + if ($effective === $account->collectInterval) { + return null; + } + + 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'); + } +} diff --git a/lib/HttpRequest.php b/lib/HttpRequest.php new file mode 100644 index 0000000..c41cbbf --- /dev/null +++ b/lib/HttpRequest.php @@ -0,0 +1,33 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +final readonly class HttpRequest { + /** + * @param array $headers + */ + public function __construct( + public string $method, + public string $url, + public array $headers = [], + public ?string $body = null, + ) { + } +} diff --git a/lib/HttpResponse.php b/lib/HttpResponse.php new file mode 100644 index 0000000..44ff3a6 --- /dev/null +++ b/lib/HttpResponse.php @@ -0,0 +1,36 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +final readonly class HttpResponse { + /** + * @param array $headers lower-case names + */ + public function __construct( + public int $status, + public array $headers, + public string $body, + ) { + } + + public function header(string $name): string { + return $this->headers[strtolower($name)] ?? ''; + } +} diff --git a/lib/HttpTransport.php b/lib/HttpTransport.php new file mode 100644 index 0000000..eaf1baa --- /dev/null +++ b/lib/HttpTransport.php @@ -0,0 +1,30 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * The only way plugin code reaches the network. + */ +interface HttpTransport { + /** + * @throws TransportError + */ + public function send(HttpRequest $request): HttpResponse; +} diff --git a/lib/Inventory.php b/lib/Inventory.php new file mode 100644 index 0000000..aca4653 --- /dev/null +++ b/lib/Inventory.php @@ -0,0 +1,28 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +final readonly class Inventory { + /** + * @param list $resources + */ + public function __construct(public array $resources, public int $requests) { + } +} diff --git a/lib/LeaseRepository.php b/lib/LeaseRepository.php new file mode 100644 index 0000000..caa191d --- /dev/null +++ b/lib/LeaseRepository.php @@ -0,0 +1,56 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * Per-account collector leases (REQ-COLL-004). A lease is taken only when no + * unexpired one is held by another run, in one statement, so two collectors + * cannot both believe they own an account. + */ +final class LeaseRepository { + public function __construct(private readonly \PDO|false $connection, private readonly Clock $clock) { + } + + 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); + + 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; + } + + /** + * When a run last took this account's lease, or 0. Written as an attempt + * starts and kept after release, so it records attempts whose results + * 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); + } + + 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); + } +} diff --git a/lib/Lifecycle.php b/lib/Lifecycle.php new file mode 100644 index 0000000..1fff5c9 --- /dev/null +++ b/lib/Lifecycle.php @@ -0,0 +1,26 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +enum Lifecycle: string { + case Active = 'active'; + case Missing = 'missing'; + case Deleted = 'deleted'; +} diff --git a/lib/Log.php b/lib/Log.php new file mode 100644 index 0000000..6599ae7 --- /dev/null +++ b/lib/Log.php @@ -0,0 +1,44 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * Plugin log lines go through cacti_log() under the CLOUD tag, so they share + * Cacti's log file, rotation, and verbosity filter. Callers pass messages + * that hold no secrets; provider error text is reduced to an error class + * before it reaches here. + */ +final class Log { + public static function debug(string $message): void { + cacti_log('DEBUG: ' . $message, false, 'CLOUD', POLLER_VERBOSITY_DEBUG); + } + + public static function info(string $message): void { + cacti_log('NOTE: ' . $message, false, 'CLOUD', POLLER_VERBOSITY_MEDIUM); + } + + public static function warning(string $message): void { + cacti_log('WARNING: ' . $message, false, 'CLOUD'); + } + + public static function error(string $message): void { + cacti_log('ERROR: ' . $message, false, 'CLOUD'); + } +} diff --git a/lib/MetricRequest.php b/lib/MetricRequest.php new file mode 100644 index 0000000..7d9a420 --- /dev/null +++ b/lib/MetricRequest.php @@ -0,0 +1,34 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * One series to read: a stored resource and a metric from the driver's + * catalog. + */ +final readonly class MetricRequest { + public function __construct( + public int $resourceId, + public string $resourceType, + public string $providerId, + public string $metric, + ) { + } +} diff --git a/lib/Observation.php b/lib/Observation.php new file mode 100644 index 0000000..0b6152c --- /dev/null +++ b/lib/Observation.php @@ -0,0 +1,49 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * The newest complete datapoint of one series. A null value is unknown, + * never zero. + */ +final readonly class Observation { + public function __construct( + public int $resourceId, + public string $metric, + public ?float $value, + public int $observedAt, + public int $fetchedAt, + ) { + } + + /** + * @param array $row + */ + public static function fromRow(array $row): ?self { + $resource = Row::int($row, 'resource_id', 0, 1); + $metric = Row::string($row, 'metric'); + + if ($resource === 0 || $metric === '') { + 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)); + } +} diff --git a/lib/ObservationRepository.php b/lib/ObservationRepository.php new file mode 100644 index 0000000..64ebbbf --- /dev/null +++ b/lib/ObservationRepository.php @@ -0,0 +1,83 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * The observation cache (REQ-STATE-001): newest complete datapoint per + * resource and metric, its provider timestamp, and when it was fetched. + * + * Each write is one statement that inserts only while the writer's lease is + * unexpired, so a collector that lost its lease cannot overwrite a newer + * run's values. An older datapoint never replaces a newer one. + */ +final class ObservationRepository { + 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) + 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', + $accountId, $holder, $now, + ], true, $this->connection); + } + + /** + * Record why series were not read this run, such as budget, keeping the + * last datapoint so freshness still ages from it. + * + * @param list $requests + */ + 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) + 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); + } + } + + 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); + + return is_array($row) ? Observation::fromRow($row) : null; + } + + /** + * @return list + */ + 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) { + $observation = Observation::fromRow($row); + + if ($observation !== null) { + $out[] = ['observation' => $observation, 'status' => Row::string($row, 'status')]; + } + } + + return $out; + } +} diff --git a/lib/Operation.php b/lib/Operation.php new file mode 100644 index 0000000..0ce8a71 --- /dev/null +++ b/lib/Operation.php @@ -0,0 +1,102 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * One provider read operation a driver may call (ADR 0002). Requests are + * matched on method, host, path, query, and for reads made through POST on + * the body, so a write operation on the same path is refused. + * + * A request with a query string matches only an operation that lists a + * query pattern, and a form body or query with a repeated parameter name + * never matches: providers differ on which copy they act on, so a pattern + * could approve one copy while the provider runs the other. + */ +final readonly class Operation { + public function __construct( + public string $name, + public string $method, + public string $host, + public string $pathPattern, + public ?string $bodyPattern = null, + public ?string $queryPattern = null, + ) { + } + + public function matches(HttpRequest $request): bool { + $parts = parse_url($request->url); + + if (!is_array($parts) || ($parts['host'] ?? '') !== $this->host || $request->method !== $this->method) { + return false; + } + + if (preg_match($this->pathPattern, $parts['path'] ?? '/') !== 1) { + return false; + } + + $query = $parts['query'] ?? ''; + + if ($query !== '' && ($this->queryPattern === null || self::repeatsName($query) || preg_match($this->queryPattern, $query) !== 1)) { + return false; + } + + $body = $request->body ?? ''; + + if ($this->bodyPattern === null) { + return $body === ''; + } + + $types = []; + + foreach ($request->headers as $name => $value) { + if (strcasecmp((string) $name, 'Content-Type') === 0) { + $types[] = strtolower(trim($value)); + } + } + + // Content-Type is a single field (RFC 9110 section 8.3); two copies + // leave it open which one the provider reads. + if (count($types) > 1) { + return false; + } + + $type = $types[0] ?? ''; + + $form = str_starts_with($type, 'application/x-www-form-urlencoded'); + + return !($form && self::repeatsName($body)) && preg_match($this->bodyPattern, $body) === 1; + } + + private static function repeatsName(string $encoded): bool { + $names = []; + + foreach (explode('&', $encoded) as $pair) { + $name = strtolower(rawurldecode(explode('=', $pair, 2)[0])); + + if (isset($names[$name])) { + return true; + } + + $names[$name] = true; + } + + return false; + } +} diff --git a/lib/OutboundPolicy.php b/lib/OutboundPolicy.php new file mode 100644 index 0000000..5d36279 --- /dev/null +++ b/lib/OutboundPolicy.php @@ -0,0 +1,82 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * Which URLs a request may go to: HTTPS only, to an exact host on the list, + * on an allowed port, with a URL that cannot be read two ways. + * + * The checks run before any name is resolved or socket opened. Hosts come + * from fixed per-provider tables and validated scope fields, never from a + * provider response or a setting. Ports other than 443 exist only for the + * test binding of the transport. + */ +final readonly class OutboundPolicy { + /** + * @param list $hosts exact lower-case host names + * @param list $ports + */ + public function __construct( + public array $hosts, + public array $ports = [443], + ) { + } + + /** + * @return array{host: string, port: int, target: string} + * @throws TransportError + */ + public function check(string $url): array { + // Control bytes, spaces, non-ASCII, and backslashes are read + // differently by different URL parsers. + if ($url === '' || strlen($url) > 8192 || preg_match('/[^\x21-\x7e]|\\\\/', $url) === 1) { + throw new TransportError('url_rejected', 'characters'); + } + + if (preg_match('#^https://([a-z0-9.-]+)(?::([0-9]{1,5}))?(/[^?\#]*)?(\?[^\#]*)?$#', $url, $m) !== 1) { + throw new TransportError('url_rejected', 'form'); + } + + $host = $m[1]; + $port = isset($m[2]) && $m[2] !== '' ? (int) $m[2] : 443; + + if (!in_array($host, $this->hosts, true)) { + throw new TransportError('host_refused', $host); + } + + if (!in_array($port, $this->ports, true)) { + throw new TransportError('url_rejected', 'port'); + } + + $path = isset($m[3]) && $m[3] !== '' ? $m[3] : '/'; + + // An encoded dot, slash, or backslash lets a server see a different + // path from the one checked here and in the operation list. + if (preg_match('/%(2e|2f|5c|00)/i', $path) === 1) { + throw new TransportError('url_rejected', 'encoded path separator'); + } + + if (preg_match('#(^|/)\.\.?(/|$)#', $path) === 1) { + throw new TransportError('url_rejected', 'dot segment'); + } + + return ['host' => $host, 'port' => $port, 'target' => $path . ($m[4] ?? '')]; + } +} diff --git a/lib/Pages.php b/lib/Pages.php new file mode 100644 index 0000000..e8a4b5a --- /dev/null +++ b/lib/Pages.php @@ -0,0 +1,90 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * Page files, realms, menu entries, and breadcrumbs. + * + * Cacti's auth.php denies any page that is not listed in a realm, so every + * page script the plugin ships must appear in exactly one realm below + * (REQ-UI-001). Pages that change accounts, credentials, or Cacti objects are + * Cloud Admin pages (REQ-UI-002). + */ +final class Pages { + public const VIEW = ['cloud_health.php']; + public const ADMIN = ['cloud_accounts.php']; + + /** + * @return list}> + */ + public static function realms(): array { + return [ + ['name' => __('Cloud View', 'cloud'), 'files' => self::VIEW], + ['name' => __('Cloud Admin', 'cloud'), 'files' => self::ADMIN], + ]; + } + + /** + * @return list + */ + public static function files(): array { + return array_merge(self::VIEW, self::ADMIN); + } + + /** + * Console > Management entries. + * + * @return array + */ + public static function menu(): array { + return [ + 'cloud_accounts.php' => __('Cloud Accounts', 'cloud'), + 'cloud_health.php' => __('Cloud Health', 'cloud'), + ]; + } + + /** + * Pages whose load re-checks the schema, matching how maintained plugins + * apply upgrades in a core that never calls plugin_*_upgrade() itself. + * + * @return list + */ + public static function upgradeTriggers(): array { + return array_merge(['plugins.php'], self::files()); + } + + /** + * @return array + */ + public static function navigation(): array { + $nav = []; + + foreach (self::menu() as $file => $title) { + $nav[$file . ':'] = [ + 'title' => $title, + 'mapping' => 'index.php:', + 'url' => $file, + 'level' => '1', + ]; + } + + return $nav; + } +} diff --git a/lib/Provider.php b/lib/Provider.php new file mode 100644 index 0000000..aa534f2 --- /dev/null +++ b/lib/Provider.php @@ -0,0 +1,90 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * Cloud providers. Values are stored in plugin_cloud_account.provider. + * + * A provider is offered for new accounts only once its release phase has + * shipped (ADR 0008); stored rows of other providers still load, so a + * downgrade never loses an account. + */ +enum Provider: string { + case DigitalOcean = 'digitalocean'; + case Aws = 'aws'; + case GoogleCloud = 'gcp'; + case Azure = 'azure'; + + /** + * @return list + */ + public static function released(): array { + return [self::DigitalOcean]; + } + + public function label(): string { + return match ($this) { + self::DigitalOcean => __('DigitalOcean', 'cloud'), + self::Aws => __('Amazon Web Services', 'cloud'), + self::GoogleCloud => __('Google Cloud', 'cloud'), + self::Azure => __('Microsoft Azure', 'cloud'), + }; + } + + /** + * Scope fields this provider's URLs are built from, each with the strict + * pattern a value must match before it is stored or used (REQ-ACCT-002). + * A list field holds comma-separated values that each match the pattern. + * + * DigitalOcean tokens are scoped to one team by DigitalOcean itself, so its + * URLs carry no account scope. + * + * @return array + */ + public function scopeFields(): array { + $uuid = '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/'; + + return match ($this) { + self::DigitalOcean => [], + self::Aws => [ + 'account_id' => ['pattern' => '/^\d{12}$/', 'list' => false], + 'regions' => ['pattern' => '/^[a-z]{2}(-gov|-iso[a-z]?)?-[a-z]+-\d{1,2}$/', 'list' => true], + ], + self::GoogleCloud => [ + 'project' => ['pattern' => '/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/', 'list' => false], + ], + self::Azure => [ + 'tenant' => ['pattern' => $uuid, 'list' => false], + 'subscription' => ['pattern' => $uuid, 'list' => false], + 'regions' => ['pattern' => '/^[a-z][a-z0-9]{1,30}$/', 'list' => true], + ], + }; + } + + /** + * @return list + */ + public function credentialSources(): array { + return match ($this) { + self::DigitalOcean => [CredentialSource::Vault, CredentialSource::File], + default => [CredentialSource::Vault, CredentialSource::File, CredentialSource::Instance], + }; + } +} diff --git a/lib/ProviderDriver.php b/lib/ProviderDriver.php new file mode 100644 index 0000000..d9496ed --- /dev/null +++ b/lib/ProviderDriver.php @@ -0,0 +1,66 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * One provider. A driver builds requests only for its listed operations and + * sends them through the transport it was given, which refuses anything else + * (ADR 0002). It reports failures as DriverError with an ErrorClass and never + * passes provider text on. + */ +interface ProviderDriver { + public function provider(): Provider; + + /** + * Hosts this account may reach, built from fixed tables and the account's + * validated scope fields. + */ + public function endpoints(Account $account): OutboundPolicy; + + /** + * Every operation the driver can call. Fixed per provider. + * + * @return list + */ + public function operations(): array; + + /** + * Test the credential and the permissions the account needs. + */ + public function verify(Account $account, Secret $credential): VerifyStatus; + + /** + * @throws DriverError + */ + public function discover(Account $account, Secret $credential): Inventory; + + /** + * @param list $requests + */ + public function collect(Account $account, Secret $credential, array $requests): CollectResult; + + /** + * Requests and cost of collecting $requests once every $intervalSeconds, + * computed without calling the provider. + * + * @param list $requests + */ + public function estimate(array $requests, int $intervalSeconds): UsageEstimate; +} diff --git a/lib/Redactor.php b/lib/Redactor.php new file mode 100644 index 0000000..b48e5d2 --- /dev/null +++ b/lib/Redactor.php @@ -0,0 +1,121 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * Removes secrets from text before it is logged or stored (REQ-CRED-005). + * + * Known secrets are replaced wherever they appear, along with their URL and + * JSON escaped forms. Authorization, cookie, and signature values are removed + * by pattern, since a signed request header holds material derived from a + * secret that is not itself on the known list. + */ +final class Redactor { + private const MASK = '[redacted]'; + + /** @var list */ + private array $known = []; + + public function add(Secret $secret): void { + $value = $secret->reveal(); + + // Every accepted credential is masked, however short: a readable + // error is worth less than a leaked secret. + if ($value === '') { + return; + } + + foreach ([$value, rawurlencode($value), urlencode($value), substr((string) json_encode($value), 1, -1)] as $form) { + if ($form !== '' && !in_array($form, $this->known, true)) { + $this->known[] = $form; + } + } + + // Longest first, so a secret containing another is masked whole. + usort($this->known, static fn (string $a, string $b): int => strlen($b) <=> strlen($a)); + } + + /** + * 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(?: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', + '/-----BEGIN [A-Z ]*PRIVATE KEY-----.*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/s', + ]; + + public function clean(string $text): string { + // Every span is found in the original text and masked once at the + // end. Applied one after another, a pass could hide material from + // the next: a known secret inside a header name would stop the + // header pattern matching, and a pattern masking part of a known + // secret would stop that secret matching whole. + $spans = []; + + foreach (self::PATTERNS as $pattern) { + if (preg_match_all($pattern, $text, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE) === false) { + return self::MASK; + } + + foreach ($matches as $match) { + // An unmatched optional group reports offset -1. + $found = isset($match['v']) && $match['v'][1] >= 0 ? $match['v'] : $match[0]; + $spans[] = [$found[1], $found[1] + strlen($found[0])]; + } + } + + foreach ($this->known as $form) { + for ($at = strpos($text, $form); $at !== false; $at = strpos($text, $form, $at + 1)) { + $spans[] = [$at, $at + strlen($form)]; + } + } + + if ($spans === []) { + return $text; + } + + sort($spans); + + /** @var list $merged */ + $merged = []; + + foreach ($spans as [$start, $stop]) { + $last = count($merged) - 1; + + if ($last >= 0 && $start <= $merged[$last][1]) { + $merged[$last] = [$merged[$last][0], max($merged[$last][1], $stop)]; + } else { + $merged[] = [$start, $stop]; + } + } + + $clean = ''; + $from = 0; + + foreach ($merged as [$start, $stop]) { + $clean .= substr($text, $from, $start - $from) . self::MASK; + $from = $stop; + } + + return $clean . substr($text, $from); + } +} diff --git a/lib/RefusingTransport.php b/lib/RefusingTransport.php new file mode 100644 index 0000000..2ee54cd --- /dev/null +++ b/lib/RefusingTransport.php @@ -0,0 +1,29 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * A transport that never sends, for drivers that are only being inspected. + */ +final class RefusingTransport implements HttpTransport { + public function send(HttpRequest $request): HttpResponse { + throw new TransportError('operation_refused', 'inspection only'); + } +} diff --git a/lib/ResourceRepository.php b/lib/ResourceRepository.php new file mode 100644 index 0000000..58bb74e --- /dev/null +++ b/lib/ResourceRepository.php @@ -0,0 +1,81 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * Resources found by discovery, with their lifecycle (REQ-STATE-003): active + * when the last discovery listed them, missing after a discovery without + * them, deleted after DELETE_AFTER such discoveries. Each write names the + * caller's lease in the statement itself, so a run that lost its lease + * between checks cannot overwrite the newer holder's inventory. + */ +final class ResourceRepository { + public const DELETE_AFTER = 3; + + public function __construct(private readonly \PDO|false $connection, private readonly Clock $clock) { + } + + public function sync(int $accountId, Inventory $inventory, LeaseRepository $leases, string $holder): bool { + $now = $this->clock->now(); + $seen = []; + + foreach ($inventory->resources as $resource) { + if (!$leases->holds($accountId, $holder)) { + 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); + + $seen[] = $resource->type . "\0" . $resource->providerId; + } + + if (!$leases->holds($accountId, $holder)) { + 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) { + 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); + } + + return true; + } + + /** + * @return array lifecycle => count + */ + 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) { + $counts[Row::string($row, 'lifecycle')] = Row::int($row, 'n'); + } + + return $counts; + } +} diff --git a/lib/Row.php b/lib/Row.php new file mode 100644 index 0000000..40e0d49 --- /dev/null +++ b/lib/Row.php @@ -0,0 +1,115 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + + +namespace Somethingwithproof\Cloud; + +/** + * Normalization rules for loose values read from Cacti's database. + * + * Only fromRow() constructors call these. Cacti stores most values as strings + * and NULL, '' and malformed text all appear in real rows, so each rule names + * what it does with them. tests/Unit/RowTest.php pins these choices; changing + * one changes comparisons everywhere a value object is built. + */ +final class Row { + /** + * Integer column. Missing, NULL, '', and anything that is not a whole + * decimal number (including '1.5', '1e3', and '12abc') yield $default, as + * does a value below $min. + * + * @param array $row + */ + public static function int(array $row, string $key, int $default = 0, int $min = PHP_INT_MIN): int { + $value = $row[$key] ?? null; + + if (is_int($value)) { + $int = $value; + } elseif (is_string($value) && preg_match('/^\s*-?\d{1,18}\s*$/', $value) === 1) { + $int = (int) $value; + } else { + return $default; + } + + return $int < $min ? $default : $int; + } + + /** + * Measured value. NULL, '', rrdtool's 'U', 'nan', and other non-numeric + * text yield null (unknown). Zero stays zero: unknown and zero are + * different measurements. + * + * @param array $row + */ + public static function float(array $row, string $key): ?float { + $value = $row[$key] ?? null; + + if (is_int($value) || is_float($value)) { + $float = (float) $value; + } elseif (is_string($value) && is_numeric(trim($value))) { + $float = (float) trim($value); + } else { + return null; + } + + return is_finite($float) ? $float : null; + } + + /** + * Text column. Missing and NULL yield ''; scalars are cast and trimmed; + * arrays and objects yield ''. + * + * @param array $row + */ + public static function string(array $row, string $key): string { + $value = $row[$key] ?? null; + + return is_scalar($value) ? trim((string) $value) : ''; + } + + /** + * Result of a db_fetch_assoc*() call, which returns false on error. An + * error reads as no rows, and non-array rows are dropped. + * + * @return list> + */ + public static function rows(mixed $rows): array { + return is_array($rows) ? array_values(array_filter($rows, 'is_array')) : []; + } + + /** + * Flag column, including Cacti checkbox settings ('on' or ''). Only 'on', + * 'yes', 'true', '1', 1 and true are true; everything else is false. + * + * @param array $row + */ + public static function bool(array $row, string $key): bool { + $value = $row[$key] ?? null; + + if (is_bool($value)) { + return $value; + } + + if (is_int($value)) { + return $value === 1; + } + + return is_string($value) && in_array(strtolower(trim($value)), ['on', 'yes', 'true', '1'], true); + } +} diff --git a/lib/Schema.php b/lib/Schema.php new file mode 100644 index 0000000..447d23e --- /dev/null +++ b/lib/Schema.php @@ -0,0 +1,314 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * Plugin tables, their migrations, and the plugin's registration records. + * + * Tables are created through api_plugin_db_table_create() so Cacti tracks them + * in plugin_db_changes and drops them on uninstall. The schema version is kept + * in its own setting because api_plugin_install() writes plugin_config.version + * before the plugin's install function runs, so that column cannot tell us + * whether the tables exist. + * + * Migrations run once each, in order, and the stored schema version moves + * past a migration only after it succeeds (REQ-LIFE-002). Every migration is + * written to be safe to repeat, so one interrupted part way is completed by + * the next run (REQ-LIFE-003). No migration calls a provider (REQ-LIFE-006). + */ +final class Schema { + public const VERSION = 1; + + public const HOOKS = [ + 'config_arrays' => 'cloud_config_arrays', + 'config_settings' => 'cloud_config_settings', + 'draw_navigation_text' => 'cloud_draw_navigation_text', + 'poller_bottom' => 'cloud_poller_bottom', + ]; + + private const PLUGIN = 'cloud'; + private const SETTING = 'cloud_schema_version'; + + 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); + + return is_numeric($value) ? (int) $value : 0; + } + + public function isCurrent(): bool { + return $this->storedVersion() === self::VERSION; + } + + /** + * Apply every pending migration, or stop at the first that fails. + * + * @param int $through the last migration to run; tests pass a lower + * number to leave an upgrade interrupted + */ + public function migrate(int $through = self::VERSION): bool { + $from = $this->storedVersion(); + + if ($from > self::VERSION) { + Log::error(sprintf('Schema version %d is newer than this code (%d); refusing to downgrade', $from, self::VERSION)); + + return false; + } + + foreach ($this->migrations() as $version => $migration) { + if ($version <= $from || $version > $through) { + continue; + } + + if (!$migration()) { + Log::error(sprintf('Schema migration %d failed; schema left at version %d', $version, $this->storedVersion())); + + return false; + } + + 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)); + } + + return true; + } + + public function recordedPluginVersion(): string { + 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); + } + + 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); + + return $hooks === count(self::HOOKS) && $realms === count(Pages::realms()); + } + + /** + * Stop Cacti from dropping the plugin tables on uninstall, and keep the + * 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); + } + + public function forgetVersion(): void { + db_execute_prepared('DELETE FROM settings WHERE name = ?', [self::SETTING], true, $this->connection); + } + + /** + * @return array schema version => migration + */ + private function migrations(): array { + return [ + 1 => fn (): bool => $this->createTables(self::tables()), + ]; + } + + /** + * Track every existing plugin table for uninstall again. + * + * Core records a table only when it creates one, so tables kept through an + * uninstall would otherwise never be dropped by a later one. The row is + * the one api_plugin_db_table_create() writes; the table has no unique + * key, so an existing row is checked for rather than replaced. + */ + 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); + } + } + } + + /** + * @param array> $tables + */ + private function createTables(array $tables): bool { + foreach ($tables as $table => $definition) { + api_plugin_db_table_create(self::PLUGIN, $table, $definition); + + if (!$this->tableExists($table)) { + Log::error(sprintf('Unable to create table %s', $table)); + + return false; + } + } + + return true; + } + + 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; + } + + /** + * Table definitions in api_plugin_db_table_create() format. + * + * State values are stored as varchar enum values, never list positions. + * Times are Unix seconds. No table holds a secret in the clear. + * + * @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]; + + return [ + 'plugin_cloud_account' => $innodb + [ + 'comment' => 'Cloud provider accounts', + 'columns' => [ + $id('id') + ['auto_increment' => true], + $text('provider', 16), + $text('name', 100), + $id('poller_id') + ['default' => '1'], + // Provider scope fields as a JSON object, validated per provider before storage. + $text('scope', 2048, '{}'), + $text('credential_source', 16), + $text('credential_file', 512), + $id('collect_interval') + ['default' => '300'], + $id('discover_interval') + ['default' => '3600'], + $id('request_share') + ['default' => '50'], + ['name' => 'monthly_ceiling', 'type' => 'double', 'NULL' => true], + $text('admin_state', 16, 'enabled'), + $text('verify_status', 32, 'never'), + $time('verified_at'), + $time('created_at'), + $time('updated_at'), + ], + 'primary' => 'id', + 'unique_keys' => [['name' => 'name', 'columns' => ['name']]], + 'keys' => [['name' => 'poller_id', 'columns' => ['poller_id']]], + ], + // Vault entries: AES-256-GCM with the account bound in the additional data. + 'plugin_cloud_secret' => $innodb + [ + 'comment' => 'Encrypted cloud credentials', + 'columns' => [ + $id('account_id'), + $text('purpose', 32, 'credential'), + ['name' => 'nonce', 'type' => 'varbinary(12)', 'NULL' => false, 'default' => ''], + ['name' => 'ciphertext', 'type' => 'mediumblob', 'NULL' => false], + ['name' => 'tag', 'type' => 'varbinary(16)', 'NULL' => false, 'default' => ''], + $text('key_id', 64), + $time('expires_at'), + $time('updated_at'), + ], + 'primary' => 'account_id`,`purpose', + ], + 'plugin_cloud_resource' => $innodb + [ + 'comment' => 'Cloud resources found by discovery', + 'columns' => [ + $id('id') + ['auto_increment' => true], + $id('account_id'), + $text('type', 64), + $text('provider_id', 255), + $text('name', 255), + $text('region', 64), + $text('lifecycle', 16, 'active'), + $id('missing_count') + ['default' => '0'], + $time('first_seen'), + $time('last_seen'), + ], + 'primary' => 'id', + 'unique_keys' => [['name' => 'account_type_resource', 'columns' => ['account_id', 'type', 'provider_id']]], + ], + // Which Cacti data source reads which resource and metric (ADR 0005). + 'plugin_cloud_series' => $innodb + [ + 'comment' => 'Cacti data sources mapped to cloud resources and metrics', + 'columns' => [ + $id('local_data_id'), + $id('account_id'), + $id('resource_id'), + $text('metric', 128), + $time('created_at'), + ], + 'primary' => 'local_data_id`,`metric', + 'keys' => [['name' => 'account_resource', 'columns' => ['account_id', 'resource_id']]], + ], + // Newest complete datapoint per resource and metric. Freshness is + // derived at read time, so a stale row cannot look current. + 'plugin_cloud_observation' => $innodb + [ + 'comment' => 'Latest cloud datapoint per resource and metric', + 'columns' => [ + $id('resource_id'), + $text('metric', 128), + ['name' => 'value', 'type' => 'double', 'NULL' => true], + $time('observed_at'), + $time('fetched_at'), + $text('status', 16, 'never'), + ], + 'primary' => 'resource_id`,`metric', + ], + 'plugin_cloud_lease' => $innodb + [ + 'comment' => 'Per-account collector leases', + 'columns' => [ + $id('account_id'), + $text('holder', 64), + $time('acquired_at'), + $time('expires_at'), + ], + 'primary' => 'account_id', + ], + 'plugin_cloud_health' => $innodb + [ + 'comment' => 'Collector and discovery status per account', + 'columns' => [ + $id('account_id'), + $time('run_started'), + $time('run_finished'), + ['name' => 'run_duration', 'type' => 'double', 'NULL' => false, 'default' => '0'], + $text('collection', 16, 'never'), + $text('error_class', 16), + $id('requests') + ['default' => '0'], + $id('series_total') + ['default' => '0'], + $id('series_read') + ['default' => '0'], + $time('discovered_at'), + $text('discovery', 16, 'never'), + $text('credential', 16, 'unknown'), + ], + 'primary' => 'account_id', + ], + // Account changes: who, when, and which fields, never their secret values. + 'plugin_cloud_audit' => $innodb + [ + 'comment' => 'Cloud account change log', + 'columns' => [ + $id('id') + ['auto_increment' => true], + $id('account_id'), + $id('user_id') + ['default' => '0'], + $time('changed_at'), + $text('action', 16), + $text('fields', 1024), + ], + 'primary' => 'id', + 'keys' => [['name' => 'account_id', 'columns' => ['account_id', 'changed_at']]], + ], + ]; + } +} diff --git a/lib/Secret.php b/lib/Secret.php new file mode 100644 index 0000000..91dc4e6 --- /dev/null +++ b/lib/Secret.php @@ -0,0 +1,83 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * A secret value: a token, key, or credential document. + * + * It refuses serialization, cloning, and export, and hides itself from + * var_dump(), print_r(), and var_export() (REQ-CRED-006). The value lives in + * a static WeakMap rather than a property, because var_export() prints an + * object's properties without asking it. It has no __toString(), so it cannot + * reach a string context by accident; reveal() is the one, greppable, way out. + */ +final class Secret { + /** @var \WeakMap|null */ + private static ?\WeakMap $values = null; + + public function __construct(#[\SensitiveParameter] string $value) { + self::$values ??= new \WeakMap(); + self::$values[$this] = $value; + } + + public function reveal(): string { + return self::$values[$this] ?? ''; + } + + public function isEmpty(): bool { + return $this->reveal() === ''; + } + + public function equals(self $other): bool { + return hash_equals($this->reveal(), $other->reveal()); + } + + /** + * @return array + */ + public function __debugInfo(): array { + return ['value' => '[redacted]']; + } + + public function __clone() { + throw new \LogicException('A secret cannot be cloned'); + } + + /** + * @return array + */ + public function __serialize(): array { + throw new \LogicException('A secret cannot be serialized'); + } + + /** + * @param array $data + */ + public function __unserialize(array $data): void { + throw new \LogicException('A secret cannot be unserialized'); + } + + /** + * @param array $state + */ + public static function __set_state(array $state): never { + throw new \LogicException('A secret cannot be exported'); + } +} diff --git a/lib/SecretRepository.php b/lib/SecretRepository.php new file mode 100644 index 0000000..1a02535 --- /dev/null +++ b/lib/SecretRepository.php @@ -0,0 +1,48 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * Encrypted vault rows. Only ciphertext passes through here. + */ +final class SecretRepository { + public const CREDENTIAL = 'credential'; + + public function __construct(private readonly \PDO|false $connection, private readonly Clock $clock) { + } + + 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); + + 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); + } + + 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; + } + + 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); + } +} diff --git a/lib/SecureFile.php b/lib/SecureFile.php new file mode 100644 index 0000000..96517ad --- /dev/null +++ b/lib/SecureFile.php @@ -0,0 +1,123 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * The checks shared by the vault key file and credential files: an absolute + * path to a regular file, not a symbolic link, not readable or writable by + * others, and of bounded size (REQ-CRED-002, REQ-CRED-003). The file is + * opened once and every check after the link test is made on that open + * handle, so a file swapped between check and read is not read. + */ +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, '/..'); + } + + /** + * @throws CredentialError + */ + public static function read(string $path, int $maxBytes): string { + $handle = self::open($path, $maxBytes); + + try { + $content = stream_get_contents($handle, $maxBytes + 1); + } finally { + fclose($handle); + } + + if (!is_string($content) || strlen($content) > $maxBytes) { + throw CredentialError::because('the file is larger than allowed'); + } + + return $content; + } + + /** + * The same checks as read(), without reading the content, for the + * health page. + * + * @throws CredentialError + */ + public static function check(string $path, int $maxBytes): void { + fclose(self::open($path, $maxBytes)); + } + + /** + * @return resource an open handle that passed every check + * + * @throws CredentialError + */ + private static function open(string $path, int $maxBytes) { + if (!self::pathAcceptable($path)) { + throw CredentialError::because('the path is not an absolute path'); + } + + clearstatcache(true, $path); + + $link = is_link($path) || file_exists($path) ? lstat($path) : false; + + if ($link === false) { + throw CredentialError::because('the file does not exist or cannot be read'); + } + + if (($link['mode'] & 0170000) === 0120000) { + throw CredentialError::because('the file is a symbolic link'); + } + + // Checked before opening too: opening a FIFO without a writer blocks. + if (($link['mode'] & 0170000) !== 0100000) { + throw CredentialError::because('the file is not a regular file'); + } + + $handle = is_readable($path) ? fopen($path, 'rb') : false; + + if ($handle === false) { + throw CredentialError::because('the file does not exist or cannot be read'); + } + + try { + $stat = fstat($handle); + + if ($stat === false || ($stat['mode'] & 0170000) !== 0100000) { + throw CredentialError::because('the file is not a regular file'); + } + + // The handle must be the file lstat() saw, not a replacement. + if ($stat['dev'] !== $link['dev'] || $stat['ino'] !== $link['ino']) { + throw CredentialError::because('the file changed while it was checked'); + } + + if (($stat['mode'] & 0006) !== 0) { + throw CredentialError::because('the file is readable or writable by other users'); + } + + if ($stat['size'] > $maxBytes) { + throw CredentialError::because('the file is larger than allowed'); + } + } catch (CredentialError $e) { + fclose($handle); + + throw $e; + } + + return $handle; + } +} diff --git a/lib/SeriesRepository.php b/lib/SeriesRepository.php new file mode 100644 index 0000000..e08ba86 --- /dev/null +++ b/lib/SeriesRepository.php @@ -0,0 +1,49 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * The series to collect: plugin data sources whose Cacti data source is + * active, on active resources (REQ-COLL-005, ADR 0005). A data source the + * plugin did not create has no row here and is never read. + */ +final class SeriesRepository { + public function __construct(private readonly \PDO|false $connection) { + } + + /** + * @return list + */ + public function enabledFor(int $accountId): array { + $requests = []; + $rows = db_fetch_assoc_prepared("SELECT DISTINCT s.resource_id, r.type, r.provider_id, s.metric + FROM plugin_cloud_series s + INNER JOIN plugin_cloud_resource r ON r.id = s.resource_id AND r.account_id = s.account_id + INNER JOIN data_template_data d ON d.local_data_id = s.local_data_id + WHERE s.account_id = ? AND r.lifecycle = ? AND d.active = 'on' + 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')); + } + + return $requests; + } +} diff --git a/lib/Settings.php b/lib/Settings.php new file mode 100644 index 0000000..595b749 --- /dev/null +++ b/lib/Settings.php @@ -0,0 +1,111 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * Plugin settings, read once per request from Cacti's settings table. + * + * Per-account values (intervals, ceilings, credential sources) live on the + * account row; these are the few that apply to the whole plugin. + */ +final readonly class Settings { + public const NAMES = [ + 'cloud_vault_key_file', + 'cloud_collector_budget', + 'cloud_uninstall_keep_tables', + ]; + + public const DEFAULT_KEY_FILE = '/etc/cacti/cloud-vault.key'; + public const DEFAULT_BUDGET = 240; + + public function __construct( + public string $vaultKeyFile, + public int $collectorBudget, + public bool $keepTablesOnUninstall, + ) { + } + + /** + * A setting that was never saved reads as its default. Keeping tables is + * the default, so an uninstall drops accounts and credentials only after + * an administrator has cleared the box (REQ-LIFE-005). + * + * @param array $row setting name => stored value, absent when never saved + */ + public static function fromRow(array $row): self { + $keyFile = Row::string($row, 'cloud_vault_key_file'); + + 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, + ); + } + + /** + * Settings tab definition for the config_settings hook (REQ-UI-003). + * + * The key file is a plain text box, not a Cacti filepath field: it lives + * on the poller that runs the collector, which need not be the server + * rendering this form, and the health page checks it there. + * + * @return array> + */ + public static function form(): array { + return [ + 'cloud_header_vault' => [ + 'friendly_name' => __('Credential Vault', 'cloud'), + 'method' => 'spacer', + ], + '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'), + 'method' => 'textbox', + 'default' => self::DEFAULT_KEY_FILE, + 'max_length' => '255', + 'size' => '60', + ], + 'cloud_header_collector' => [ + 'friendly_name' => __('Collector', 'cloud'), + 'method' => 'spacer', + ], + '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'), + 'method' => 'textbox', + 'default' => (string) self::DEFAULT_BUDGET, + 'filter' => FILTER_VALIDATE_INT, + 'options' => ['options' => ['min_range' => 10, 'max_range' => 3600]], + 'max_length' => '4', + 'size' => '4', + ], + 'cloud_header_uninstall' => [ + 'friendly_name' => __('Uninstall', 'cloud'), + 'method' => 'spacer', + ], + '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'), + 'method' => 'checkbox', + 'default' => 'on', + ], + ]; + } +} diff --git a/lib/SettingsRepository.php b/lib/SettingsRepository.php new file mode 100644 index 0000000..11c3ee3 --- /dev/null +++ b/lib/SettingsRepository.php @@ -0,0 +1,45 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * Reads the plugin settings straight from Cacti's settings table. + * + * read_config_option() substitutes a form default for a setting that was + * never saved, and only when the config_settings hook has run in this + * request, which the poller does not do. Reading the rows keeps "never + * saved" distinguishable from "saved empty", so Settings::fromRow() applies + * the same defaults everywhere. + */ +final class SettingsRepository { + public function __construct(private readonly \PDO|false $connection) { + } + + 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) { + $row[Row::string($setting, 'name')] = $setting['value'] ?? null; + } + + return Settings::fromRow($row); + } +} diff --git a/lib/SocketTransport.php b/lib/SocketTransport.php new file mode 100644 index 0000000..4bf1328 --- /dev/null +++ b/lib/SocketTransport.php @@ -0,0 +1,306 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * HTTPS over stream_socket_client() with its own HTTP/1.1 reader (ADR 0009), + * from the milestone 1 spike. One request per connection, certificate and + * host name verification on, no redirects followed, the connect and TLS + * handshake inside one total deadline, at most 64 KiB of headers, a body cap, + * strict Content-Length, and strict chunked decoding: PHP's dechunk filter + * passes a malformed chunk through as data. + */ +final class SocketTransport implements HttpTransport { + private const MAX_HEADER_BYTES = 65536; + + /** + * @param ?string $caFile a CA bundle for the test binding only; production + * uses OpenSSL's configured trust store + */ + public function __construct( + private readonly OutboundPolicy $policy, + private readonly float $connectTimeout = 5.0, + private readonly float $totalTimeout = 30.0, + private readonly int $maxBytes = 5242880, + private readonly ?string $caFile = null, + ) { + } + + public function send(HttpRequest $request): HttpResponse { + // The policy is checked before anything resolves or connects. + $url = $this->policy->check($request->url); + $method = $request->method; + $headers = $request->headers; + $body = $request->body; + $deadline = microtime(true) + $this->totalTimeout; + $host = $url['host']; + $port = $url['port']; + $target = $url['target']; + + if (preg_match('/^[A-Z]{3,7}$/', $method) !== 1) { + throw new TransportError('header_rejected', 'method'); + } + + // 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"; + 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'); + } + $request .= "$name: $value\r\n"; + } + if ($body !== null || in_array($method, array('POST', 'PUT', 'PATCH'), true)) { + $request .= 'Content-Length: ' . strlen($body ?? '') . "\r\n"; + } + $request .= "\r\n" . ($body ?? ''); + + $ssl = [ + 'verify_peer' => true, + 'verify_peer_name' => true, + 'allow_self_signed' => false, + 'peer_name' => $host, + 'SNI_enabled' => true, + 'disable_compression' => true, + ]; + + if ($this->caFile !== null) { + $ssl['cafile'] = $this->caFile; + } + + $ctx = stream_context_create(['ssl' => $ssl]); + + // The connect and TLS handshake share the total budget. Checked before + // the warning collector is installed, so a throw cannot leave it behind. + $connectBudget = min($this->connectTimeout, $deadline - microtime(true)); + if ($connectBudget <= 0) { + throw new TransportError('total_timeout'); + } + + $warnings = array(); + set_error_handler(function (int $no, string $message) use (&$warnings): bool { + $warnings[] = $message; + + return true; + }); + try { + $fp = stream_socket_client("tls://$host:$port", $errno, $errstr, $connectBudget, STREAM_CLIENT_CONNECT, $ctx); + } finally { + restore_error_handler(); + } + if ($fp === false) { + $message = implode(' | ', array_merge($warnings, array("$errno $errstr"))); + throw new TransportError(self::classify($message), self::clean($message)); + } + + try { + // A peer that stops reading must not hold the write past the deadline. + for ($off = 0; $off < strlen($request); $off += $n) { + $left = $deadline - microtime(true); + if ($left <= 0) { + throw new TransportError('total_timeout'); + } + stream_set_timeout($fp, (int) $left, (int) (fmod($left, 1) * 1e6)); + $n = @fwrite($fp, substr($request, $off, 65536)); + if (stream_get_meta_data($fp)['timed_out']) { + throw new TransportError('total_timeout'); + } + if ($n === false || $n === 0) { + throw new TransportError('write_failed'); + } + } + + // Informational (1xx) responses come before the final one and are + // skipped; their bytes count towards the same header limit. + $raw = ''; + $headBytes = 0; + while (true) { + $headEnd = strpos($raw, "\r\n\r\n"); + while ($headEnd === false) { + if ($headBytes + strlen($raw) > self::MAX_HEADER_BYTES) { + throw new TransportError('headers_too_large'); + } + if (feof($fp)) { + throw new TransportError('malformed', 'connection closed in headers'); + } + $raw .= $this->readSome($fp, $deadline); + $headEnd = strpos($raw, "\r\n\r\n"); + } + $headBytes += $headEnd + 4; + if ($headBytes > self::MAX_HEADER_BYTES) { + throw new TransportError('headers_too_large'); + } + [$status, $responseHeaders] = self::parseHead(substr($raw, 0, $headEnd)); + $rest = substr($raw, $headEnd + 4); + if ($status === 101) { + // No request asks for an upgrade. + throw new TransportError('malformed', 'unexpected 101'); + } + if ($status >= 200) { + break; + } + $raw = $rest; + } + + // These responses end with their headers whatever Content-Length + // says (RFC 9112 section 6.3). + if ($method === 'HEAD' || $status === 204 || $status === 304) { + return new HttpResponse($status, $responseHeaders, ''); + } + + if ($status >= 300 && $status < 400) { + throw new TransportError('redirect_refused', (string) $status); + } + + $chunked = str_contains(strtolower($responseHeaders['transfer-encoding'] ?? ''), 'chunked'); + $length = null; + if (!$chunked && isset($responseHeaders['content-length'])) { + if (preg_match('/^\d{1,12}$/', $responseHeaders['content-length']) !== 1) { + throw new TransportError('malformed', 'content-length'); + } + $length = (int) $responseHeaders['content-length']; + if ($length > $this->maxBytes) { + throw new TransportError('too_large', 'content-length ' . $length); + } + } + + // The raw (still chunked) body is capped too, so chunk framing + // cannot be used to stream an unbounded amount through the filter. + while (!feof($fp) && ($length === null || strlen($rest) < $length)) { + $rest .= $this->readSome($fp, $deadline); + if (strlen($rest) > $this->maxBytes + ($chunked ? 65536 : 0)) { + throw new TransportError('too_large', 'over ' . $this->maxBytes . ' bytes'); + } + } + if ($length !== null && strlen($rest) < $length) { + throw new TransportError('malformed', 'body shorter than content-length'); + } + $out = $chunked ? self::dechunk($rest) : ($length === null ? $rest : substr($rest, 0, $length)); + if (strlen($out) > $this->maxBytes) { + throw new TransportError('too_large', 'over ' . $this->maxBytes . ' bytes'); + } + + return new HttpResponse($status, $responseHeaders, $out); + } finally { + fclose($fp); + } + } + + /** + * fread() on a socket returns whatever has arrived, so checking the + * deadline between reads bounds a server that sends one byte at a time. + * + * @param resource $fp + */ + private function readSome($fp, float $deadline): string { + $left = $deadline - microtime(true); + if ($left <= 0) { + throw new TransportError('total_timeout'); + } + stream_set_timeout($fp, (int) $left, (int) (fmod($left, 1) * 1e6)); + // A peer that closes without TLS close_notify raises a warning on + // some builds; the caller sees EOF either way. + $chunk = @fread($fp, 8192); + if (stream_get_meta_data($fp)['timed_out']) { + throw new TransportError('total_timeout'); + } + + return $chunk === false ? '' : $chunk; + } + + /** + * @return array{0: int, 1: array} + */ + private static function parseHead(string $head): array { + $lines = explode("\r\n", $head); + if (preg_match('#^HTTP/1\.[01] (\d{3})(?: |$)#', array_shift($lines), $m) !== 1) { + throw new TransportError('malformed', 'status line'); + } + $headers = array(); + foreach ($lines as $line) { + $pos = strpos($line, ':'); + if ($pos === false || $pos === 0 || $line[0] === ' ' || $line[0] === "\t") { + throw new TransportError('malformed', 'header line'); + } + $name = strtolower(substr($line, 0, $pos)); + $value = trim(substr($line, $pos + 1), " \t"); + // Two Content-Length values that disagree are a framing attack. + if ($name === 'content-length' && isset($headers[$name]) && $headers[$name] !== $value) { + throw new TransportError('malformed', 'conflicting content-length'); + } + $headers[$name] = $value; + } + + return array((int) $m[1], $headers); + } + + /** + * Strict RFC 9112 chunked decoding. Trailer fields are checked for + * shape and ignored; the empty line that ends them is required. + */ + private static function dechunk(string $raw): string { + $out = ''; + $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) { + throw new TransportError('malformed', 'chunk size'); + } + // At most eight hex digits, so the value always fits an int. + $size = (int) hexdec($m[1]); + $pos = $eol + 2; + if ($size === 0) { + while (true) { + $eol = strpos($raw, "\r\n", $pos); + if ($eol === false) { + throw new TransportError('malformed', 'chunked terminator'); + } + $line = substr($raw, $pos, $eol - $pos); + $pos = $eol + 2; + if ($line === '') { + return $out; + } + if (preg_match('/^[!#$%&\'*+.^_`|~0-9A-Za-z-]+:/', $line) !== 1) { + throw new TransportError('malformed', 'trailer line'); + } + } + } + if (strlen($raw) < $pos + $size + 2 || substr($raw, $pos + $size, 2) !== "\r\n") { + throw new TransportError('malformed', 'chunk data'); + } + $out .= substr($raw, $pos, $size); + $pos += $size + 2; + } + } + + private static function classify(string $message): string { + return match (true) { + str_contains($message, 'certificate verify failed') => 'tls_verify', + str_contains($message, 'did not match expected') => 'tls_name', + str_contains($message, 'timed out') => 'connect_timeout', + str_contains($message, 'refused') => 'connect_refused', + default => 'open_failed', + }; + } + + private static function clean(string $message): string { + return substr((string) preg_replace('/[\x00-\x1f\x7f]+/', ' ', $message), 0, 400); + } +} diff --git a/lib/SystemClock.php b/lib/SystemClock.php new file mode 100644 index 0000000..158b91c --- /dev/null +++ b/lib/SystemClock.php @@ -0,0 +1,26 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +final class SystemClock implements Clock { + public function now(): int { + return time(); + } +} diff --git a/lib/TransportError.php b/lib/TransportError.php new file mode 100644 index 0000000..afd6ca1 --- /dev/null +++ b/lib/TransportError.php @@ -0,0 +1,39 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * A request the transport refused or could not complete. The kind is a fixed + * code; the detail is diagnostic text from the local side only (never a + * response body) and still passes through the Redactor before it is logged. + */ +final class TransportError extends \RuntimeException { + public function __construct(public readonly string $kind, string $detail = '') { + parent::__construct($kind . ($detail !== '' ? ': ' . $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, + 'malformed', 'too_large', 'headers_too_large' => ErrorClass::Malformed, + default => ErrorClass::Transient, + }; + } +} diff --git a/lib/UsageEstimate.php b/lib/UsageEstimate.php new file mode 100644 index 0000000..776c815 --- /dev/null +++ b/lib/UsageEstimate.php @@ -0,0 +1,29 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +final readonly class UsageEstimate { + public function __construct( + public int $requestsPerCollection, + public int $requestsPerMonth, + public float $monthlyCost, + ) { + } +} diff --git a/lib/Vault.php b/lib/Vault.php new file mode 100644 index 0000000..b600676 --- /dev/null +++ b/lib/Vault.php @@ -0,0 +1,72 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * AES-256-GCM encryption of stored credentials (REQ-CRED-001, ADR 0007). + * + * Each value gets a fresh random 96-bit nonce. The additional data names the + * account and the purpose of the value, so a ciphertext copied to another + * account's row, or from a cached token to the credential slot, fails to + * decrypt instead of being used. + */ +final class Vault { + public const NONCE_BYTES = 12; + public const TAG_BYTES = 16; + + private const CIPHER = 'aes-256-gcm'; + + public function __construct(private readonly VaultKey $key) { + } + + public function encrypt(Secret $secret, int $accountId, string $purpose, int $expiresAt = 0): VaultEntry { + $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); + + if ($ciphertext === false || strlen($tag) !== self::TAG_BYTES) { + throw CredentialError::because('the credential could not be encrypted'); + } + + return new VaultEntry($nonce, $ciphertext, $tag, $this->key->id(), $expiresAt); + } + + /** + * @throws CredentialError + */ + public function decrypt(VaultEntry $entry, int $accountId, string $purpose): Secret { + if ($entry->keyId !== $this->key->id()) { + 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)); + + if ($plain === false) { + throw CredentialError::because('the stored credential failed its integrity check'); + } + + return new Secret($plain); + } + + private static function additionalData(int $accountId, string $purpose): string { + return 'plugin_cloud/vault/v1/account/' . $accountId . '/' . $purpose; + } +} diff --git a/lib/VaultEntry.php b/lib/VaultEntry.php new file mode 100644 index 0000000..a533820 --- /dev/null +++ b/lib/VaultEntry.php @@ -0,0 +1,49 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * One encrypted vault value as stored in plugin_cloud_secret. + */ +final readonly class VaultEntry { + public function __construct( + public string $nonce, + public string $ciphertext, + public string $tag, + public string $keyId, + public int $expiresAt = 0, + ) { + } + + /** + * @param array $row + */ + public static function fromRow(array $row): ?self { + $nonce = $row['nonce'] ?? null; + $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) { + return null; + } + + return new self($nonce, $ciphertext, $tag, Row::string($row, 'key_id'), Row::int($row, 'expires_at', 0, 0)); + } +} diff --git a/lib/VaultKey.php b/lib/VaultKey.php new file mode 100644 index 0000000..2967568 --- /dev/null +++ b/lib/VaultKey.php @@ -0,0 +1,83 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * The vault key, read from a file the administrator creates. The plugin never + * creates or writes it. The file holds exactly 32 raw bytes or 64 hex + * characters, optionally followed by one newline. + */ +final class VaultKey { + private function __construct(private readonly Secret $key) { + } + + /** + * @throws CredentialError + */ + public static function fromFile(string $path): self { + $content = SecureFile::read($path, 65); + + if (strlen($content) === 32) { + return new self(new Secret($content)); + } + + $hex = rtrim($content, "\n"); + + if (strlen($hex) === 64 && ctype_xdigit($hex)) { + return new self(new Secret((string) hex2bin($hex))); + } + + throw CredentialError::because('the key file must hold exactly 32 bytes or 64 hexadecimal characters'); + } + + public static function fromBytes(#[\SensitiveParameter] string $bytes): self { + if (strlen($bytes) !== 32) { + throw CredentialError::because('a vault key is 32 bytes'); + } + + return new self(new Secret($bytes)); + } + + public function bytes(): string { + return $this->key->reveal(); + } + + /** + * Identifies the key a ciphertext was written with, without revealing it, + * so a replaced key file is reported as such rather than as corruption. + */ + public function id(): string { + return substr(hash_hmac('sha256', 'plugin_cloud vault key id', $this->key->reveal()), 0, 16); + } + + /** + * @return array + */ + public function __debugInfo(): array { + return ['key' => '[redacted]']; + } + + /** + * @return array + */ + public function __serialize(): array { + throw new \LogicException('A vault key cannot be serialized'); + } +} diff --git a/lib/Verifier.php b/lib/Verifier.php new file mode 100644 index 0000000..9dbab5b --- /dev/null +++ b/lib/Verifier.php @@ -0,0 +1,65 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * Verify on the account page: resolve the credential, ask the driver, and + * record one fixed status (REQ-ACCT-004). Exceptions never carry provider + * text out of here; anything unexpected is a configuration status. + */ +final class Verifier { + public function __construct( + private readonly Drivers $drivers, + private readonly CredentialStore $credentials, + private readonly AccountRepository $accounts, + ) { + } + + public function verify(Account $account, int $userId): VerifyStatus { + $status = $this->status($account); + + $this->accounts->recordVerify($account->id, $status, $userId); + + return $status; + } + + private function status(Account $account): VerifyStatus { + try { + $driver = $this->drivers->for($account); + + if ($driver === null) { + return VerifyStatus::Config; + } + + return $driver->verify($account, $this->credentials->credentialFor($account)); + } catch (CredentialError) { + return VerifyStatus::Config; + } catch (DriverError $error) { + return VerifyStatus::fromError($error->errorClass); + } catch (TransportError $error) { + return VerifyStatus::fromError($error->errorClass()); + } catch (\Throwable $error) { + // The class only: an unexpected message may carry provider text. + Log::warning(sprintf('Account %d: verify failed unexpectedly (%s)', $account->id, $error::class)); + + return VerifyStatus::Config; + } + } +} diff --git a/lib/VerifyStatus.php b/lib/VerifyStatus.php new file mode 100644 index 0000000..3342adb --- /dev/null +++ b/lib/VerifyStatus.php @@ -0,0 +1,59 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +namespace Somethingwithproof\Cloud; + +/** + * The recorded result of Verify. Each status has one fixed message, so the + * account page never shows provider error text (REQ-ACCT-004). + */ +enum VerifyStatus: string { + case Never = 'never'; + case Ok = 'ok'; + case Invalid = 'invalid'; + case Permission = 'permission'; + case Unreachable = 'unreachable'; + case Throttled = 'throttled'; + case Malformed = 'malformed'; + case Config = 'config'; + + public static function fromError(ErrorClass $error): self { + return match ($error) { + ErrorClass::Auth => self::Invalid, + ErrorClass::Permission => self::Permission, + ErrorClass::Throttled => self::Throttled, + ErrorClass::Transient => self::Unreachable, + ErrorClass::Malformed => self::Malformed, + ErrorClass::Config => self::Config, + }; + } + + public function message(): string { + return match ($this) { + self::Never => __('Not verified yet.', 'cloud'), + 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::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/build_gettext.sh b/locales/build_gettext.sh new file mode 100755 index 0000000..ebcb7c7 --- /dev/null +++ b/locales/build_gettext.sh @@ -0,0 +1,111 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2026 Thomas Vincent +# SPDX-License-Identifier: GPL-2.0-or-later +# +# This file is part of plugin_cloud, a plugin for Cacti. +# https://github.com/somethingwithproof/plugin_cloud +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the Free +# Software Foundation; either version 2 of the License, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +# more details. +# +# Regenerate locales/po/cacti.pot from every PHP file at depth 2 or less, the +# scan the Cacti plugin gettext builds use, merge it into each catalog +# locales/po/.po, and compile each catalog to +# locales/LC_MESSAGES/.mo, where Cacti loads plugin translations. +# +# With --check, change nothing and fail when the template is out of date, a +# catalog misses or has a fuzzy entry, a format string does not match, or a +# compiled catalog differs from its source. + +set -eu + +BASE_PATH=$(cd "$(dirname "$0")/.." && pwd) +POT=locales/po/cacti.pot + +cd "$BASE_PATH" +mkdir -p locales/po + +command -v xgettext >/dev/null 2>&1 || { echo "ERROR: Unable to locate xgettext (install GNU gettext)" >&2; exit 1; } + +VERSION=$(sed -n 's/^version *= *//p' INFO) + +generate() { + # 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) + + 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" +} + +if [ "${1:-}" = "--check" ]; then + tmp=$(mktemp) + generate "$tmp" + + if ! diff -u "$POT" "$tmp"; then + rm -f "$tmp" + echo "ERROR: $POT is out of date; run locales/build_gettext.sh and commit the result" >&2 + exit 1 + fi + + rm -f "$tmp" + echo "$POT is up to date" + + command -v msgunfmt >/dev/null 2>&1 || { echo "ERROR: Unable to locate msgunfmt (install GNU gettext)" >&2; exit 1; } + rc=0 + + for po in locales/po/*.po; do + [ -f "$po" ] || continue + locale=$(basename "$po" .po) + mo=locales/LC_MESSAGES/$locale.mo + + # Every template entry translated, none fuzzy, formats intact. + msgfmt --check -o /dev/null "$po" || { echo "ERROR: $po does not compile" >&2; rc=1; continue; } + msgcmp "$po" "$POT" || { echo "ERROR: $po misses entries of $POT; run locales/build_gettext.sh" >&2; rc=1; } + [ -z "$(msgattrib --only-fuzzy --no-obsolete "$po")" ] || { echo "ERROR: $po has fuzzy entries" >&2; rc=1; } + [ -z "$(msgattrib --untranslated --no-obsolete "$po")" ] || { echo "ERROR: $po has untranslated entries" >&2; rc=1; } + + # Cacti's __() formats a message only when it holds a plain placeholder + # (%d, %s, ...); a positional one (%1$d) is printed literally, so + # translations keep the message's argument order. + # --no-wrap keeps each msgstr on one line, so a long translation's + # continuation lines are checked too. + if msgattrib --no-obsolete --no-wrap "$po" | grep -E '^msgstr' | grep -qE '%[0-9]+\$'; then + echo "ERROR: $po uses a positional placeholder such as %1\$d, which Cacti prints literally" >&2 + rc=1 + fi + + # The compiled catalog holds the same messages as its source; compared + # decompiled, because gettext versions lay the binary out differently. + if [ ! -f "$mo" ] || [ "$(msgunfmt "$mo")" != "$(msgfmt -o - "$po" | msgunfmt)" ]; then + echo "ERROR: $mo is missing or out of date; run locales/build_gettext.sh" >&2 + rc=1 + fi + done + + [ $rc -eq 0 ] && echo "catalogs are complete and compiled" + exit $rc +fi + +generate "$POT" +echo "Updated $POT" + +mkdir -p locales/LC_MESSAGES + +for po in locales/po/*.po; do + [ -f "$po" ] || continue + msgmerge --quiet --update --no-wrap --backup=none "$po" "$POT" + msgfmt -o "locales/LC_MESSAGES/$(basename "$po" .po).mo" "$po" + echo "Compiled $po" +done diff --git a/locales/index.php b/locales/index.php new file mode 100644 index 0000000..d4377e6 --- /dev/null +++ b/locales/index.php @@ -0,0 +1,20 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +header('Location: ../index.php'); diff --git a/locales/po/cacti.pot b/locales/po/cacti.pot new file mode 100644 index 0000000..3a468bd --- /dev/null +++ b/locales/po/cacti.pot @@ -0,0 +1,424 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) YEAR Thomas Vincent +# This file is distributed under the same license as the cloud package. +# FIRST AUTHOR , YEAR. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: cloud 0.1.0-dev\n" +"Report-Msgid-Bugs-To: https://github.com/somethingwithproof/plugin_cloud/issues\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: Thomas Vincent \n" +"Language-Team: Thomas Vincent \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + +#: cloud_accounts.php +msgid "Name: another account already uses this name." +msgstr "" + +#: cloud_accounts.php +#, php-format +msgid "The account was saved, but the credential was not stored: %s" +msgstr "" + +#: cloud_accounts.php +msgid "The account was saved." +msgstr "" + +#: cloud_accounts.php +msgid "The account could not be saved." +msgstr "" + +#: cloud_accounts.php +msgid "The account and its collected data were deleted. Its Cacti devices and graphs were left in place." +msgstr "" + +#: lib/AccountInput.php +msgid "Provider: choose one of the listed providers." +msgstr "" + +#: lib/AccountInput.php +msgid "Name: enter 1 to 100 characters without control characters." +msgstr "" + +#: lib/AccountInput.php +msgid "Poller: only the main poller can collect cloud accounts in this release." +msgstr "" + +#: lib/AccountInput.php +#, php-format +msgid "%s: the value does not have the form this provider uses." +msgstr "" + +#: lib/AccountInput.php +msgid "Credential Source: choose one this provider supports." +msgstr "" + +#: lib/AccountInput.php +msgid "Credential File: enter an absolute path without control characters, at most 512 characters." +msgstr "" + +#: lib/AccountInput.php +#, php-format +msgid "%s: enter whole seconds from %d to %d." +msgstr "" + +#: lib/AccountInput.php lib/AccountsPage.php +msgid "Collection Interval" +msgstr "" + +#: lib/AccountInput.php lib/AccountsPage.php +msgid "Discovery Interval" +msgstr "" + +#: lib/AccountInput.php +msgid "Request Share: enter a whole percentage from 1 to 100." +msgstr "" + +#: lib/AccountInput.php +msgid "Monthly Ceiling: enter an amount of zero or more, or leave it blank for none." +msgstr "" + +#: lib/AccountInput.php +msgid "AWS Account ID" +msgstr "" + +#: lib/AccountInput.php +msgid "Regions" +msgstr "" + +#: lib/AccountInput.php +msgid "Project ID" +msgstr "" + +#: lib/AccountInput.php +msgid "Tenant ID" +msgstr "" + +#: lib/AccountInput.php +msgid "Subscription ID" +msgstr "" + +#: lib/AccountsPage.php lib/Pages.php +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 "" + +#: lib/AccountsPage.php +msgid "Provider" +msgstr "" + +#: lib/AccountsPage.php +msgid "State" +msgstr "" + +#: lib/AccountsPage.php +msgid "Verify" +msgstr "" + +#: lib/AccountsPage.php lib/HealthPage.php +msgid "No cloud accounts yet." +msgstr "" + +#: lib/AccountsPage.php lib/HealthPage.php +msgid "Disabled" +msgstr "" + +#: lib/AccountsPage.php +msgid "Enabled" +msgstr "" + +#: lib/AccountsPage.php +msgid "Delete" +msgstr "" + +#: lib/AccountsPage.php +#, php-format +msgid "Cloud Account: %s" +msgstr "" + +#: lib/AccountsPage.php +msgid "New Cloud Account" +msgstr "" + +#: lib/AccountsPage.php +msgid "Credential Source" +msgstr "" + +#: lib/AccountsPage.php +msgid "Credential File" +msgstr "" + +#: lib/AccountsPage.php +msgid "A credential is stored. Leave blank to keep it." +msgstr "" + +#: lib/AccountsPage.php +msgid "Paste the token or key to store in the vault." +msgstr "" + +#: lib/AccountsPage.php +msgid "Request Share" +msgstr "" + +#: lib/AccountsPage.php +msgid "Monthly Ceiling" +msgstr "" + +#: lib/AccountsPage.php +msgid "Save" +msgstr "" + +#: lib/AccountsPage.php +msgid "None stored" +msgstr "" + +#: lib/AccountsPage.php +msgid "Stored in the vault" +msgstr "" + +#: lib/AccountsPage.php +msgid "File on the poller" +msgstr "" + +#: lib/AccountsPage.php +msgid "Instance identity" +msgstr "" + +#: lib/CredentialSource.php +msgid "Stored in the plugin vault" +msgstr "" + +#: lib/CredentialSource.php +msgid "Credential file on the poller" +msgstr "" + +#: lib/CredentialSource.php +msgid "Instance identity of the poller" +msgstr "" + +#: lib/HealthPage.php +msgid "Cloud Warnings" +msgstr "" + +#: lib/HealthPage.php +msgid "No warnings." +msgstr "" + +#: lib/HealthPage.php +msgid "Cloud Collection" +msgstr "" + +#: lib/HealthPage.php +msgid "Account" +msgstr "" + +#: lib/HealthPage.php +msgid "Collection" +msgstr "" + +#: lib/HealthPage.php +msgid "Data" +msgstr "" + +#: lib/HealthPage.php +msgid "Discovery" +msgstr "" + +#: lib/HealthPage.php +msgid "Last Run" +msgstr "" + +#: lib/HealthPage.php +msgid "Requests" +msgstr "" + +#: lib/HealthPage.php +msgid "Resources" +msgstr "" + +#: lib/HealthPage.php +msgid "Series Read" +msgstr "" + +#: lib/HealthPage.php +msgid "Never" +msgstr "" + +#: lib/HealthPage.php +#, php-format +msgid "%d seconds ago" +msgstr "" + +#: lib/HealthPage.php +#, php-format +msgid "%d minutes ago" +msgstr "" + +#: lib/HealthPage.php +#, php-format +msgid "%d hours ago" +msgstr "" + +#: lib/HealthPage.php +#, php-format +msgid "%d days ago" +msgstr "" + +#: lib/HealthWarnings.php +#, php-format +msgid "The vault key file cannot be used: %s. Accounts that store credentials in the vault cannot be verified or collected here." +msgstr "" + +#: lib/HealthWarnings.php +#, php-format +msgid "%s: the credential file cannot be used: %s." +msgstr "" + +#: lib/HealthWarnings.php +#, php-format +msgid "%s: the collection interval of %d seconds is shorter than the poller interval of %d seconds, so it is collected every %d seconds." +msgstr "" + +#: lib/HealthWarnings.php +#, php-format +msgid "%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." +msgstr "" + +#: lib/Pages.php +msgid "Cloud View" +msgstr "" + +#: lib/Pages.php +msgid "Cloud Admin" +msgstr "" + +#: lib/Pages.php +msgid "Cloud Health" +msgstr "" + +#: lib/Provider.php +msgid "DigitalOcean" +msgstr "" + +#: lib/Provider.php +msgid "Amazon Web Services" +msgstr "" + +#: lib/Provider.php +msgid "Google Cloud" +msgstr "" + +#: lib/Provider.php +msgid "Microsoft Azure" +msgstr "" + +#: lib/Settings.php +msgid "Credential Vault" +msgstr "" + +#: lib/Settings.php +msgid "Vault Key File" +msgstr "" + +#: lib/Settings.php +msgid "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." +msgstr "" + +#: lib/Settings.php +msgid "Collector" +msgstr "" + +#: lib/Settings.php +msgid "Collector Time Budget" +msgstr "" + +#: lib/Settings.php +msgid "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." +msgstr "" + +#: lib/Settings.php +msgid "Uninstall" +msgstr "" + +#: lib/Settings.php +msgid "Keep Plugin Tables on Uninstall" +msgstr "" + +#: lib/Settings.php +msgid "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." +msgstr "" + +#: lib/VerifyStatus.php +msgid "Not verified yet." +msgstr "" + +#: lib/VerifyStatus.php +msgid "The credential works and has the permissions this account needs." +msgstr "" + +#: lib/VerifyStatus.php +msgid "The provider rejected the credential. It may be wrong, expired, or revoked." +msgstr "" + +#: lib/VerifyStatus.php +msgid "The credential works but lacks a permission this account needs." +msgstr "" + +#: lib/VerifyStatus.php +msgid "The provider could not be reached. Check the network path and outbound policy from the poller." +msgstr "" + +#: lib/VerifyStatus.php +msgid "The provider is throttling requests. Try again later." +msgstr "" + +#: lib/VerifyStatus.php +msgid "The provider sent a response the plugin could not read." +msgstr "" + +#: lib/VerifyStatus.php +msgid "The account or its credential is not configured correctly." +msgstr "" + +#: setup.php +#, php-format +msgid "The Cloud plugin requires PHP %s or later. This server runs PHP %s, so the plugin was not installed or enabled." +msgstr "" + +#: setup.php +#, php-format +msgid "The Cloud plugin requires the PHP extensions %s, which this server does not load, so the plugin was not installed or enabled." +msgstr "" + +#: setup.php +msgid "Cloud" +msgstr "" + +#: setup.php +msgid "The Cloud plugin is not enabled." +msgstr "" + +#: setup.php +#, php-format +msgid "The Cloud plugin requires PHP %s or later." +msgstr "" + +#: setup.php +msgid "Management" +msgstr "" diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 0000000..342a476 --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,38 @@ +# SPDX-FileCopyrightText: 2026 Thomas Vincent +# SPDX-License-Identifier: GPL-2.0-or-later +# +# This file is part of plugin_cloud, a plugin for Cacti. +# https://github.com/somethingwithproof/plugin_cloud +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the Free +# Software Foundation; either version 2 of the License, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +# more details. + +# Static analysis of the plugin classes against a Cacti core checkout. +# CACTI_PATH=/path/to/cacti phpstan analyse -c phpstan.neon +# Core is scanned for symbols only. +parameters: + level: 9 + phpVersion: 80200 + paths: + - lib + - setup.php + - include/unbooted-uninstall.php + scanDirectories: + - %env.CACTI_PATH%/lib + - %env.CACTI_PATH%/include + bootstrapFiles: + - tests/phpstan-bootstrap.php + excludePaths: + analyseAndScan: + - %env.CACTI_PATH%/include/vendor/* + - %env.CACTI_PATH%/include/fa/* + - %env.CACTI_PATH%/include/js/* + - %env.CACTI_PATH%/include/themes/* + treatPhpDocTypesAsCertain: false diff --git a/phpunit-integration.xml b/phpunit-integration.xml new file mode 100644 index 0000000..b7fba06 --- /dev/null +++ b/phpunit-integration.xml @@ -0,0 +1,17 @@ + + + + + + + + + tests/Integration + + + diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..ae5eaa4 --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,29 @@ + + + + + + + + + tests/Security + tests/Unit + tests/Transport + + + + + lib + + + diff --git a/poller_cloud.php b/poller_cloud.php new file mode 100644 index 0000000..bc4c5d5 --- /dev/null +++ b/poller_cloud.php @@ -0,0 +1,87 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * The cloud collector for one poller, started by the poller_bottom hook: + * + * php plugins/cloud/poller_cloud.php [--poller=N] [--force] [--debug] + * + * One instance per poller, through Cacti's process registry. This file must + * parse on PHP 8.0 and refuses to run below 8.2. + */ + +chdir(__DIR__ . '/../..'); + +require('./include/cli_check.php'); +require_once($config['base_path'] . '/lib/poller.php'); +require_once($config['base_path'] . '/plugins/cloud/setup.php'); + +ini_set('max_execution_time', '0'); + +$cloud_poller = (int) $config['poller_id']; +$cloud_force = false; + +foreach (array_slice($_SERVER['argv'], 1) as $cloud_arg) { + if (strpos($cloud_arg, '--poller=') === 0) { + $cloud_poller = (int) substr($cloud_arg, 9); + } elseif ($cloud_arg === '--force') { + $cloud_force = true; + } 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); + exit(1); + } +} + +if (cloud_refuse_unsupported()) { + exit(1); +} + +cloud_boot(); + +if (!$cloud_force && !api_plugin_is_enabled('cloud')) { + exit(0); +} + +if ($cloud_poller < 1) { + exit(0); +} + +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'); + 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); + exit(0); +} + +try { + $cloud_result = cloud_collector($cloud_poller)->run($cloud_poller, $cloud_budget); +} finally { + 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); + +exit(0); diff --git a/setup.php b/setup.php new file mode 100644 index 0000000..309d54c --- /dev/null +++ b/setup.php @@ -0,0 +1,353 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Cacti includes this file on every request, on whatever PHP version the site + * runs. It must parse on PHP 8.0 (CI lints it there), and nothing under lib/ + * is loaded until cloud_boot() has confirmed PHP 8.2 or later (ADR 0004). + * Every hook and lifecycle function therefore starts with that check, so an + * unsupported runtime gets a refusal instead of a parse error that would take + * down the whole Cacti UI. + */ + +function cloud_php_supported(): bool { + return version_compare(PHP_VERSION, '8.2.0', '>='); +} + +/** + * Extensions the plugin needs that PHP can be built without. Cacti 1.2.31's + * composer.json already requires each of them (REQ-COMPAT-006). ext-json is + * always present since PHP 8.0, and ext-curl is deliberately not used + * (ADR 0009): TLS goes through stream sockets, which need ext-openssl. + * + * @return list + */ +function cloud_required_extensions(): array { + return array('openssl'); +} + +/** + * @return list + */ +function cloud_missing_extensions(): array { + $missing = array(); + + foreach (cloud_required_extensions() as $extension) { + if (!extension_loaded($extension)) { + $missing[] = $extension; + } + } + + return $missing; +} + +function cloud_boot(): bool { + if (!cloud_php_supported() || cloud_missing_extensions() !== array()) { + return false; + } + + require_once(__DIR__ . '/include/autoload.php'); + + return true; +} + +/** + * Refuse with a message naming what is missing. + * + * Used by the lifecycle functions only. Hook shims return silently instead, + * because they run on every page and a refused plugin must not flood the log. + */ +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'); + } 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'); + } else { + return false; + } + + cacti_log('ERROR: ' . $message, false, 'CLOUD'); + + if (PHP_SAPI === 'cli') { + fwrite(STDERR, $message . PHP_EOL); + } elseif (function_exists('raise_message')) { + raise_message('cloud_php', $message, MESSAGE_LEVEL_ERROR); + } + + return true; +} + +/** + * @return array + */ +function plugin_cloud_version(): array { + $info = parse_ini_file(__DIR__ . '/INFO', true); + + if (!is_array($info) || !isset($info['info']) || !is_array($info['info'])) { + return array(); + } + + $version = array(); + + foreach ($info['info'] as $key => $value) { + $version[(string) $key] = is_scalar($value) ? (string) $value : ''; + } + + return $version; +} + +function plugin_cloud_install(): void { + if (cloud_refuse_unsupported()) { + return; + } + + plugin_cloud_upgrade(true); +} + +function plugin_cloud_check_config(): bool { + if (cloud_refuse_unsupported()) { + return false; + } + + return plugin_cloud_upgrade(true); +} + +/** + * Common start of every page script, after include/auth.php has authorized + * the realm. Refuses on an unsupported runtime or a disabled plugin, because + * Cacti keeps plugin realms registered while a plugin is disabled. + */ +function cloud_page_start(): bool { + if (cloud_boot() && api_plugin_is_enabled('cloud')) { + return true; + } + + top_header(); + + 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')) . ''; + + html_end_box(); + + bottom_footer(); + + return false; +} + +/** + * State-changing actions are accepted only as POST (REQ-UI-004). A GET that + * names one is sent back to the page without effect. + * + * @param list $actions + */ +function cloud_require_post(string $page, array $actions): void { + $action = (string) get_nfilter_request_var('action'); + + if (in_array($action, $actions, true) && $_SERVER['REQUEST_METHOD'] !== 'POST') { + header('Location: ' . $page); + exit; + } +} + +function cloud_credentials(): \Somethingwithproof\Cloud\CredentialStore { + return new \Somethingwithproof\Cloud\CredentialStore(new \Somethingwithproof\Cloud\SecretRepository(false, new \Somethingwithproof\Cloud\SystemClock()), cloud_settings()->vaultKeyFile); +} + +function cloud_accounts(): \Somethingwithproof\Cloud\AccountRepository { + return new \Somethingwithproof\Cloud\AccountRepository(false, new \Somethingwithproof\Cloud\SystemClock()); +} + +function cloud_settings(): \Somethingwithproof\Cloud\Settings { + return (new \Somethingwithproof\Cloud\SettingsRepository(false))->load(); +} + +/** + * Bring the schema, hooks, and realms up to the code's version. + * + * Cacti 1.2.31 never calls this itself; check_config and the config_arrays + * hook do. Fresh installs take the same path as upgrades. The version stored + * in plugin_config changes only after every migration has succeeded, so an + * interrupted run is finished by the next one. + * + * $grant gives newly registered realms to the current user. Only install and + * check_config pass it: both run from the Plugins page, which needs plugin + * management. A repair triggered from config_arrays can run for anyone who + * opens a plugin page, so it must never grant anything. + */ +function plugin_cloud_upgrade(bool $grant = false): bool { + if (!cloud_boot()) { + return false; + } + + $info = plugin_cloud_version(); + $schema = new \Somethingwithproof\Cloud\Schema(false); + + if ($schema->isCurrent() && $schema->recordedPluginVersion() === $info['version'] && $schema->hooksRegistered()) { + return true; + } + + if (!$schema->migrate()) { + return false; + } + + $schema->trackTables(); + + cloud_setup_hooks($grant); + + $schema->recordPluginVersion($info['version'], $info['author'], $info['homepage']); + + return true; +} + +/** + * Register hooks and realms. + * + * Kept procedural and named *_setup_* because api_plugin_register_hook() and + * api_plugin_register_realm() refuse callers whose function name does not + * contain install, upgrade, or setup. + */ +function cloud_setup_hooks(bool $grant = false): void { + global $config; + + // Registering a hook replicates plugin config, which needs core lib/poller.php. + if (!function_exists('replicate_out')) { + include_once($config['library_path'] . '/poller.php'); + } + + foreach (\Somethingwithproof\Cloud\Schema::HOOKS as $hook => $function) { + api_plugin_register_hook('cloud', $hook, $function, 'setup.php'); + } + + foreach (\Somethingwithproof\Cloud\Pages::realms() as $realm) { + api_plugin_register_realm('cloud', implode(',', $realm['files']), $realm['name'], $grant); + } +} + +/** + * Uninstall never touches cloud resources or provider accounts. Core drops + * the tracked plugin tables afterwards unless the administrator left "Keep + * Plugin Tables on Uninstall" checked, which is the default. + */ +function plugin_cloud_uninstall(): void { + if (!cloud_boot()) { + include_once(__DIR__ . '/include/unbooted-uninstall.php'); + cloud_uninstall_unbooted(); + + return; + } + + $schema = new \Somethingwithproof\Cloud\Schema(false); + + if (cloud_settings()->keepTablesOnUninstall) { + $schema->untrackTables(); + + \Somethingwithproof\Cloud\Log::info('Uninstall kept the plugin tables as configured'); + } else { + $schema->forgetVersion(); + } +} + +function cloud_config_arrays(): void { + global $menu; + + if (!cloud_boot()) { + return; + } + + foreach (\Somethingwithproof\Cloud\Pages::menu() as $file => $title) { + $menu[__('Management')]['plugins/cloud/' . $file] = $title; + } + + if (in_array(get_current_page(), \Somethingwithproof\Cloud\Pages::upgradeTriggers(), true)) { + plugin_cloud_upgrade(); + } +} + +function cloud_config_settings(): void { + global $tabs, $settings; + + if (!cloud_boot()) { + return; + } + + $tabs['cloud'] = __('Cloud', 'cloud'); + $settings['cloud'] = \Somethingwithproof\Cloud\Settings::form(); +} + +/** + * @param array $nav + * @return array + */ +function cloud_draw_navigation_text($nav) { + if (!cloud_boot()) { + return $nav; + } + + return array_merge($nav, \Somethingwithproof\Cloud\Pages::navigation()); +} + +/** + * poller_bottom hook: start this poller's collector in the background + * (REQ-COLL-001). The collector itself skips accounts of other pollers. + */ +function cloud_poller_bottom(): void { + global $config; + + if (!cloud_boot()) { + return; + } + + if (!function_exists('exec_background')) { + include_once($config['library_path'] . '/poller.php'); + } + + // exec_background() silently does nothing for a binary that does not + // exist, so a bare 'php' fallback would never start the collector. + $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'); + + return; + } + + // Core accepts an argument array and escapes each element, although its + // docblock declares a string. + // @phpstan-ignore argument.type + exec_background($php, array('-q', __DIR__ . '/poller_cloud.php', '--poller=' . (int) $config['poller_id'])); +} + +function cloud_collector(int $pollerId): \Somethingwithproof\Cloud\Collector { + $clock = new \Somethingwithproof\Cloud\SystemClock(); + + return new \Somethingwithproof\Cloud\Collector( + cloud_accounts(), + \Somethingwithproof\Cloud\Drivers::production(), + cloud_credentials(), + new \Somethingwithproof\Cloud\LeaseRepository(false, $clock), + new \Somethingwithproof\Cloud\ResourceRepository(false, $clock), + new \Somethingwithproof\Cloud\SeriesRepository(false), + new \Somethingwithproof\Cloud\ObservationRepository(false), + new \Somethingwithproof\Cloud\HealthRepository(false), + new \Somethingwithproof\Cloud\Redactor(), + $clock, + 'poller' . $pollerId . '-' . getmypid() . '-' . bin2hex(random_bytes(4)) + ); +} diff --git a/tests/Integration/LifecycleTest.php b/tests/Integration/LifecycleTest.php new file mode 100644 index 0000000..75f57d7 --- /dev/null +++ b/tests/Integration/LifecycleTest.php @@ -0,0 +1,265 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +// The version INFO declares, which Cacti records as the installed version. +define('CLOUD_VERSION', (string) (parse_ini_file(dirname(__DIR__, 2) . '/INFO', true)['info']['version'] ?? '')); + +const CLOUD_TABLES = [ + 'plugin_cloud_account', + 'plugin_cloud_audit', + 'plugin_cloud_health', + 'plugin_cloud_lease', + 'plugin_cloud_observation', + 'plugin_cloud_resource', + 'plugin_cloud_secret', + 'plugin_cloud_series', +]; + +const CLOUD_HOOKS = ['config_arrays', 'config_settings', 'draw_navigation_text', 'poller_bottom']; + +beforeEach(function () { + lifecycle('reset'); +}); + +afterAll(function () { + lifecycle('reset'); +}); + +it('installs fresh with tracked tables, hooks, and both realms, leaving the plugin disabled', function () { + $state = lifecycle('install'); + + expect($state['plugin']['status'])->toEqual('4') + ->and($state['plugin']['version'])->toEqual(CLOUD_VERSION) + ->and($state['schema'])->toEqual('1') + ->and(array_keys($state['tables']))->toBe(CLOUD_TABLES) + ->and($state['tracked'])->toBe(CLOUD_TABLES) + ->and(array_keys($state['hooks']))->toBe(CLOUD_HOOKS) + ->and($state['realms'])->toEqual([ + 'cloud_accounts.php' => 'Cloud Admin', + 'cloud_health.php' => 'Cloud View', + ]) + ->and($state['admin'])->toBe(2); +}); + +it('enables and disables through core, keeping data on disable', function () { + lifecycle('install'); + lifecycle('seed'); + + $enabled = lifecycle('enable'); + expect($enabled['plugin']['status'])->toEqual('1') + ->and(array_values(array_unique(array_map('strval', $enabled['hooks']))))->toBe(['1']); + + $disabled = lifecycle('disable'); + expect($disabled['plugin']['status'])->toEqual('4') + ->and($disabled['tables']['plugin_cloud_account'])->toBe(1); +}); + +it('upgrades from an older recorded version and is idempotent on repeated runs', function () { + lifecycle('install'); + lifecycle('seed'); + lifecycle('set_version', '0.0'); + + $first = lifecycle('upgrade'); + expect($first['result'])->toBeTrue() + ->and($first['plugin']['version'])->toEqual(CLOUD_VERSION); + + foreach ([lifecycle('upgrade'), lifecycle('upgrade')] as $run) { + expect($run['result'])->toBeTrue() + ->and($run['tables'])->toBe($first['tables']) + ->and($run['hooks'])->toBe($first['hooks']) + ->and($run['realms'])->toBe($first['realms']) + ->and($run['tracked'])->toBe(CLOUD_TABLES); + } + + expect($first['tables']['plugin_cloud_account'])->toBe(1); +}); + +it('re-registers hooks and realms that went missing', function () { + lifecycle('install'); + + $missing = lifecycle('drop_registrations'); + expect($missing['hooks'])->toBe([]); + + $state = lifecycle('upgrade'); + + expect($state['result'])->toBeTrue() + ->and(array_keys($state['hooks']))->toBe(CLOUD_HOOKS) + ->and($state['realms'])->toHaveCount(2); +}); + +it('finishes an upgrade that was interrupted after creating only some tables', function () { + lifecycle('install'); + lifecycle('seed'); + lifecycle('drop_table', 'plugin_cloud_health'); + lifecycle('drop_table', 'plugin_cloud_audit'); + lifecycle('set_schema', '0'); + lifecycle('set_version', '0.0'); + + $state = lifecycle('upgrade'); + + expect($state['result'])->toBeTrue() + ->and(array_keys($state['tables']))->toBe(CLOUD_TABLES) + ->and($state['tables']['plugin_cloud_account'])->toBe(1) + ->and($state['schema'])->toEqual('1') + ->and($state['plugin']['version'])->toEqual(CLOUD_VERSION); +}); + +it('does not advance past a migration that did not run', function () { + lifecycle('install'); + lifecycle('set_schema', '0'); + + $stopped = lifecycle('migrate_through', '0'); + expect($stopped['result'])->toBeTrue() + ->and($stopped['schema'])->toEqual('0'); + + $finished = lifecycle('upgrade'); + expect($finished['schema'])->toEqual('1'); +}); + +it('refuses a schema newer than the code and leaves the recorded version alone', function () { + lifecycle('install'); + lifecycle('set_schema', '99'); + lifecycle('set_version', '0.0'); + + $state = lifecycle('upgrade'); + + expect($state['result'])->toBeFalse() + ->and($state['plugin']['version'])->toEqual('0.0') + ->and($state['schema'])->toEqual('99'); +}); + +it('keeps tables on uninstall by default, and drops them only when the box was cleared', function () { + lifecycle('install'); + lifecycle('seed'); + + $kept = lifecycle('uninstall'); + expect(array_keys($kept['tables']))->toBe(CLOUD_TABLES) + ->and($kept['tables']['plugin_cloud_account'])->toBe(1) + ->and($kept['tracked'])->toBe([]) + ->and($kept['hooks'])->toBe([]) + ->and($kept['realms'])->toBe([]); + + // A reinstall reuses the kept tables and their rows. + $reinstalled = lifecycle('install'); + expect($reinstalled['plugin']['status'])->toEqual('4') + ->and($reinstalled['tables']['plugin_cloud_account'])->toBe(1) + ->and($reinstalled['tracked'])->toBe(CLOUD_TABLES); + + lifecycle('set_setting', 'cloud_uninstall_keep_tables='); + + $dropped = lifecycle('uninstall'); + expect($dropped['plugin'])->toBeEmpty() + ->and($dropped['tables'])->toBe([]) + ->and($dropped['schema'])->toBeEmpty(); +}); + +it('stores credentials only as ciphertext and audits every account change', function () { + lifecycle('install'); + + $state = lifecycle('credential_flow'); + + expect($state['result']['read_back'])->toBeTrue() + ->and($state['result']['leaks'])->toBe([]) + ->and($state['result']['audit'])->toBe(['create', 'credential', 'update', 'verify']) + ->and($state['result']['account_gone'])->toBeTrue() + ->and($state['tables']['plugin_cloud_secret'])->toBe(0) + ->and($state['tables']['plugin_cloud_audit'])->toBe(5); +}); + +it('collects only what is due, owned, enabled, mapped, and leased', function () { + lifecycle('install'); + + $r = lifecycle('collector_flow')['result']; + + expect($r['run1'])->toBe(['accounts' => 1, 'skipped' => 0, 'stopped_early' => false]) + ->and($r['discoveries'])->toBe(1) + ->and($r['resources'])->toBe(2) + ->and($r['others'])->toBe(0) + // Inside the collection interval nothing runs. + ->and($r['collected_early'])->toBe([]) + // Only the active, plugin-mapped data source is read; discovery is not due again. + ->and($r['collected'])->toBe(['d1/cpu']) + ->and($r['collected_at_200'])->toBe(1) + ->and($r['collected_at_296'])->toBe(2) + ->and($r['discoveries_after'])->toBe(1) + ->and((float) $r['observation']['value'])->toBe(42.5) + ->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['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']) + ->and($r['health_unchanged'])->toBeTrue() + ->and($r['order_run1']['stopped_early'])->toBeTrue() + ->and($r['order'])->toBe(['Second', 'Main']); +}); + +it('honours keep tables on uninstall when the runtime is refused', function () { + lifecycle('install'); + lifecycle('seed'); + + $kept = lifecycle('uninstall_unbooted'); + expect($kept['tables']['plugin_cloud_account'])->toBe(1) + ->and($kept['tracked'])->toBe([]); + + lifecycle('reset'); + lifecycle('install'); + lifecycle('set_setting', 'cloud_uninstall_keep_tables='); + + $dropped = lifecycle('uninstall_unbooted'); + expect($dropped['tables'])->toBe([]) + ->and($dropped['schema'])->toBeEmpty(); +}); + +it('grants realms on install but never on a repair a viewer triggers', function () { + expect(lifecycle('install')['admin'])->toBe(2); + + $repair = lifecycle('repair_as_viewer'); + expect($repair['realms'])->toHaveCount(2) + ->and($repair['result'])->toBe(['viewer_realms' => 0]); +}); + +it('exits at once when a collector already runs on the poller', function () { + lifecycle('install'); + lifecycle('enable'); + + $r = lifecycle('collector_second')['result']; + + expect($r['rc'])->toBe(0) + ->and($r['seconds'])->toBeLessThan(5.0) + ->and($r['leases'])->toBe(0) + ->and($r['leases_when_free'])->toBe(1); +}); + +it('leaves no partial result when a run is killed mid-account, and the next run continues', function () { + lifecycle('install'); + + $r = lifecycle('collector_kill')['result']; + + expect($r['victim_rc'])->not->toBe(0) + // The dead run still holds its lease, and wrote no health or value. + ->and($r['after_kill']['lease']['holder'])->toBe('victim') + ->and($r['after_kill']['health'])->toBeEmpty() + ->and($r['after_kill']['observations'])->toBe([]) + ->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']]); +}); diff --git a/tests/Pest.php b/tests/Pest.php new file mode 100644 index 0000000..c77d3c9 --- /dev/null +++ b/tests/Pest.php @@ -0,0 +1,22 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Pest configuration. Bootstraps are named by phpunit.xml. + */ diff --git a/tests/Security/SourceRulesTest.php b/tests/Security/SourceRulesTest.php new file mode 100644 index 0000000..9ef94ec --- /dev/null +++ b/tests/Security/SourceRulesTest.php @@ -0,0 +1,251 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Source rules from docs/PLAN.md "Code structure" and ADR 0004 that a parser + * can check. The PHP 8.0 parse of the entry points themselves is proven by the + * CI lint job on a real PHP 8.0; these checks catch the same mistakes earlier + * and cover the rules a lint cannot. + */ + +function cloud_root(): string { + return dirname(__DIR__, 2); +} + +/** + * @return list plugin PHP files outside tests/, relative to the root + */ +function cloud_sources(): array { + $files = []; + $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(cloud_root(), FilesystemIterator::SKIP_DOTS)); + + 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/')) { + $files[] = $relative; + } + } + + sort($files); + + return $files; +} + +/** + * @return list files Cacti may include before the PHP version check + */ +function cloud_entry_points(): array { + return array_values(array_filter(cloud_sources(), fn (string $f) => !str_starts_with($f, 'lib/'))); +} + +it('keeps every PHP source file within the gettext scan depth', function () { + foreach (cloud_sources() as $file) { + expect(substr_count($file, '/'))->toBeLessThanOrEqual(1, $file); + } +}); + +it('keeps entry points free of PHP 8.1 and later syntax', function () { + $banned = [T_ENUM => 'enum', T_READONLY => 'readonly']; + + foreach (cloud_entry_points() as $file) { + $tokens = PhpToken::tokenize((string) file_get_contents(cloud_root() . '/' . $file)); + + foreach ($tokens as $i => $token) { + expect(isset($banned[$token->id]))->toBeFalse("$file:{$token->line} uses {$token->text}"); + + // "never" as a return type and "new" in an initializer are 8.1. + if ($token->is(T_STRING) && strtolower($token->text) === 'never') { + $previous = $tokens[$i - 1]->is(T_WHITESPACE) ? $tokens[$i - 2] : $tokens[$i - 1]; + expect($previous->text)->not->toBe(':', "$file:{$token->line} uses never"); + } + } + } +}); + +it('uses no PHP 8.3 or later features anywhere', function () { + foreach (cloud_sources() as $file) { + $source = (string) file_get_contents(cloud_root() . '/' . $file); + $tokens = PhpToken::tokenize($source); + + expect($source)->not->toContain('json_validate(') + ->and($source)->not->toContain('#[\\Override]') + ->and($source)->not->toContain('#[Override]'); + + foreach ($tokens as $i => $token) { + if (!$token->is(T_CONST)) { + continue; + } + + // A typed constant has two identifiers between const and "=". + $names = 0; + + for ($j = $i + 1; $j < count($tokens) && $tokens[$j]->text !== '='; $j++) { + $names += $tokens[$j]->is(T_STRING) ? 1 : 0; + } + + expect($names)->toBe(1, "$file:{$token->line} declares a typed constant"); + } + } +}); + +it('defines exactly one class, interface, or enum per lib file, named after the file', function () { + foreach (glob(cloud_root() . '/lib/*.php') as $path) { + $tokens = PhpToken::tokenize((string) file_get_contents($path)); + $names = []; + + foreach ($tokens as $i => $token) { + if ($token->is([T_CLASS, T_INTERFACE, T_ENUM, T_TRAIT]) && !$tokens[$i - 1]->is(T_DOUBLE_COLON)) { + $next = $tokens[$i + 1]->is(T_WHITESPACE) ? $tokens[$i + 2] : $tokens[$i + 1]; + + if ($next->is(T_STRING)) { + $names[] = $next->text; + } + } + } + + expect($names)->toBe([basename($path, '.php')], basename($path)) + ->and((string) file_get_contents($path))->toContain("namespace Somethingwithproof\\Cloud;"); + } +}); + +it('keeps lib classes away from request variables and globals', function () { + foreach (glob(cloud_root() . '/lib/*.php') as $path) { + $source = (string) file_get_contents($path); + + expect($source)->not->toMatch('/\$_(REQUEST|GET|POST|SESSION|SERVER|COOKIE)\b/', basename($path)) + ->and($source)->not->toMatch('/\bglobal\s+\$/', basename($path)) + ->and($source)->not->toContain('$GLOBALS', basename($path)); + } +}); + +it('issues SQL only from repository and schema classes, through prepared helpers', function () { + foreach (cloud_sources() as $file) { + $source = (string) file_get_contents(cloud_root() . '/' . $file); + + expect($source)->not->toMatch('/\bdb_(execute|fetch_cell|fetch_row|fetch_assoc)\s*\(/', $file); + + // include/unbooted-uninstall.php is the one exception: it runs where + // lib/ cannot load (see its header). + $repository = str_starts_with($file, 'lib/') && preg_match('/^(Schema|\w+Repository)\.php$/', basename($file)) === 1; + + if (!$repository && $file !== 'include/unbooted-uninstall.php') { + expect($source)->not->toMatch('/\bdb_\w+_prepared\s*\(/', $file); + } + } +}); + +it('passes the cloud text domain to every translated plugin string', function () { + // Labels intentionally reused from core keep the core domain. + $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]))); + + foreach ($tokens as $i => $token) { + if (!$token->is(T_STRING) || $token->text !== '__' || ($tokens[$i + 1]->text ?? '') !== '(' || ($tokens[$i - 1]->is(T_FUNCTION))) { + continue; + } + + $depth = 0; + $last = null; + + for ($j = $i + 1; $j < count($tokens); $j++) { + $depth += $tokens[$j]->text === '(' ? 1 : ($tokens[$j]->text === ')' ? -1 : 0); + + if ($depth === 0) { + break; + } + + if ($depth === 1 && $tokens[$j]->text !== ',' && $tokens[$j]->text !== '(') { + $last = $tokens[$j]; + } + } + + $first = $tokens[$i + 2]; + + if ($first->is(T_CONSTANT_ENCAPSED_STRING) && in_array(trim($first->text, '\'"'), $core, true)) { + continue; + } + + expect($last?->text)->toBe("'cloud'", "$file:{$token->line}"); + } + } +}); + +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) { + expect($pot)->toContain('msgid "' . $msgid . '"'); + } +}); + +it('formats translated strings with __() itself, never sprintf(__())', function () { + // Core's __() hands the text domain to sprintf(), so a placeholder in + // sprintf(__("%d", "cloud"), $n) takes "cloud" and prints 0 or the + // domain. The values go inside the call: __("%d", $n, "cloud"). + foreach (cloud_sources() as $file) { + expect((string) file_get_contents(cloud_root() . '/' . $file))->not->toContain('sprintf(__(', $file); + } +}); + +it('uses plain placeholders in translated strings, because core\'s __() does not format positional ones', function () { + // __() only formats a string that has %d, %s, and the like. A string with + // only %1$d placeholders comes back raw. + foreach (cloud_sources() as $file) { + $source = (string) file_get_contents(cloud_root() . '/' . $file); + + preg_match_all("/__\\('((?:[^'\\\\]|\\\\.)*)'/", $source, $texts); + + foreach ($texts[1] as $text) { + expect($text)->not->toMatch('/%[0-9]+\$/', $file); + } + } +}); + +it('logs through cacti_log() under the CLOUD tag only', function () { + foreach (cloud_sources() as $file) { + $code = ''; + + foreach (PhpToken::tokenize((string) file_get_contents(cloud_root() . '/' . $file)) as $token) { + $code .= $token->is([T_COMMENT, T_DOC_COMMENT]) ? '' : $token->text; + } + + preg_match_all('/\bcacti_log\s*\((.*?)\);/s', $code, $calls); + + foreach ($calls[1] as $arguments) { + expect(str_contains($arguments, "'CLOUD'"))->toBeTrue($file); + } + } +}); + +it('ships no Composer runtime dependencies', function () { + $manifest = cloud_root() . '/composer.json'; + + if (is_file($manifest)) { + $require = json_decode((string) file_get_contents($manifest), true)['require'] ?? []; + + foreach (array_keys($require) as $package) { + expect($package === 'php' || str_starts_with($package, 'ext-'))->toBeTrue($package); + } + } + + expect(is_dir(cloud_root() . '/vendor'))->toBeFalse(); +}); diff --git a/tests/Transport/SocketTransportTest.php b/tests/Transport/SocketTransportTest.php new file mode 100644 index 0000000..b34bb69 --- /dev/null +++ b/tests/Transport/SocketTransportTest.php @@ -0,0 +1,236 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * The transport against local HTTPS servers, extending the milestone 1 + * spike's cases (REQ-TEST-003). The servers and certificates are the spike's + * own. The test server is reached through the constructor's test binding (a + * CA file and an extra port), never through a setting. + */ + +use Somethingwithproof\Cloud\GuardedTransport; +use Somethingwithproof\Cloud\HttpRequest; +use Somethingwithproof\Cloud\Operation; +use Somethingwithproof\Cloud\OutboundPolicy; +use Somethingwithproof\Cloud\SocketTransport; +use Somethingwithproof\Cloud\TransportError; + +const CLOUD_SPIKE = __DIR__ . '/../transport-spike'; + +function cloud_free_port(): int { + $s = stream_socket_server('tcp://127.0.0.1:0'); + $name = (string) stream_socket_get_name($s, false); + fclose($s); + + return (int) substr($name, strrpos($name, ':') + 1); +} + +/** + * @param list $args + */ +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); + + // A refused probe raises a warning, which the suite treats as a failure. + set_error_handler(static fn (): bool => true); + + try { + for ($i = 0; $i < 100; $i++) { + $fp = stream_socket_client('tcp://127.0.0.1:' . $port, $e, $s, 0.1); + + if ($fp !== false) { + fclose($fp); + + return $port; + } + + usleep(50000); + } + } finally { + restore_error_handler(); + } + + throw new RuntimeException('test server did not start'); +} + +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'); +} + +function cloud_kind(callable $call): string { + try { + $call(); + } catch (TransportError $e) { + return $e->kind; + } + + return 'sent'; +} + +beforeAll(function () { + $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); + + if ($rc !== 0) { + throw new RuntimeException('make-certs failed'); + } +}); + +afterAll(function () { + foreach ($GLOBALS['__cloud_servers'] as $server) { + proc_terminate($server); + } +}); + +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'])); + + expect($r->status)->toBe(200) + ->and($r->body)->toBe('{"ok":true}') + ->and($r->header('X-Spike'))->toBe('one'); +}); + +it('ends HEAD and 204 responses at their headers whatever Content-Length says', function () { + $port = cloud_server(['tls', $GLOBALS['__cloud_certs'] . '/good.pem']); + + 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'); +}); + +it('decodes chunked bodies, skips 1xx responses, and returns error bodies', function () { + $port = cloud_server(['tls', $GLOBALS['__cloud_certs'] . '/good.pem']); + $t = cloud_transport($port); + + expect($t->send(new HttpRequest('GET', "https://127.0.0.1:$port/chunked"))->body)->not->toBe('') + ->and($t->send(new HttpRequest('GET', "https://127.0.0.1:$port/early-hints"))->status)->toBe(200) + ->and($t->send(new HttpRequest('GET', "https://127.0.0.1:$port/error"))->status)->toBeGreaterThanOrEqual(400); +}); + +it('refuses untrusted certificates, wrong names, and redirects', function () { + $self = cloud_server(['tls', $GLOBALS['__cloud_certs'] . '/selfsigned.pem']); + $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'); +}); + +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); +})->with([ + ['/bad-terminator', 'malformed'], + ['/bad-chunk', 'malformed'], + ['/dup-length', 'malformed'], + ['/huge-header?n=1048576', 'headers_too_large'], + ['/header-flood', 'headers_too_large'], + ['/big?n=20000000&len=0', 'too_large'], + ['/big-withheld?n=20000000', 'too_large'], +]); + +it('stops slow and stalled responses at the total timeout', function (string $path) { + $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') + ->and(microtime(true) - $start)->toBeLessThan(3.5); +})->with(['/stall', '/slow-body', '/slow-headers']); + +it('stops a TLS handshake that is never answered within the deadline', function () { + $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']) + ->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'); +}); + +it('refuses URLs outside the policy without opening a socket', function (string $url, string $kind) { + // Port 9 on this host has nothing listening: a refusal that tried to + // connect would report a connect error instead. + $t = new SocketTransport(new OutboundPolicy(['api.example.com'], [443]), 0.5, 1.0); + + expect(cloud_kind(fn () => $t->send(new HttpRequest('GET', $url))))->toBe($kind); +})->with([ + ['http://api.example.com/v2', 'url_rejected'], + ['https://other.example.com/v2', 'host_refused'], + ['https://127.0.0.1:9/v2', 'host_refused'], + ['https://user:pass@api.example.com/v2', 'url_rejected'], + ['https://api.example.com/v2#frag', 'url_rejected'], + ['https://api.example.com\\@evil.example/', 'url_rejected'], + ['https://api.example.com:9/v2', 'url_rejected'], + ['https://api.example.com:+443/v2', 'url_rejected'], + ["https://api.example.com/v2\r\nX: 1", 'url_rejected'], + ['https://api.example.com/v2/../admin', 'url_rejected'], + ['https://api.example.com/v2/%2e%2e/admin', 'url_rejected'], + ['https://api.example.com/v2/%2E./admin', 'url_rejected'], + ['https://api.example.com/v2%2fdroplets', 'url_rejected'], + ['https://api.example.com/v2%5cdroplets', 'url_rejected'], + ['https://API.example.com/v2', 'url_rejected'], + ["https://api.example.com/\xc3\xa9", 'url_rejected'], +]); + +it('refuses operations that are not on the driver list before they are sent', function () { + $sent = new class implements \Somethingwithproof\Cloud\HttpTransport { + public int $calls = 0; + + public function send(HttpRequest $request): \Somethingwithproof\Cloud\HttpResponse { + $this->calls++; + + return new \Somethingwithproof\Cloud\HttpResponse(200, [], ''); + } + }; + $guard = new GuardedTransport($sent, [ + new Operation('List droplets', 'GET', 'api.example.com', '#^/v2/droplets$#'), + new Operation('Read metrics', 'POST', 'api.example.com', '#^/$#', '/^Action=GetMetricData(&|$)/'), + new Operation('Page droplets', 'GET', 'api.example.com', '#^/v2/droplets$#', null, '/^page=\d+&per_page=\d+$/'), + ]); + $form = ['Content-Type' => 'application/x-www-form-urlencoded']; + + $guard->send(new HttpRequest('GET', 'https://api.example.com/v2/droplets')); + $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') + ->and($sent->calls)->toBe(3); +}); diff --git a/tests/Unit/AccountTest.php b/tests/Unit/AccountTest.php new file mode 100644 index 0000000..c920688 --- /dev/null +++ b/tests/Unit/AccountTest.php @@ -0,0 +1,217 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +use Somethingwithproof\Cloud\Account; +use Somethingwithproof\Cloud\AccountInput; +use Somethingwithproof\Cloud\AdminState; +use Somethingwithproof\Cloud\CredentialSource; +use Somethingwithproof\Cloud\Provider; +use Somethingwithproof\Cloud\VerifyStatus; + +function cloud_account_input(array $override = []): array { + return $override + [ + 'provider' => 'digitalocean', + 'name' => 'Production', + 'poller_id' => '1', + 'credential_source' => 'vault', + 'credential_file' => '', + 'collect_interval' => '300', + 'discover_interval' => '3600', + 'request_share' => '50', + 'monthly_ceiling' => '', + 'enabled' => 'on', + ]; +} + +it('builds an account from valid input', function () { + $parsed = AccountInput::parse(cloud_account_input(), 0, Provider::released()); + + expect($parsed->errors)->toBe([]) + ->and($parsed->account?->provider)->toBe(Provider::DigitalOcean) + ->and($parsed->account?->scope)->toBe([]) + ->and($parsed->account?->adminState)->toBe(AdminState::Enabled) + ->and($parsed->account?->monthlyCeiling)->toBeNull(); +}); + +it('refuses each invalid field with a message naming it', function (array $override, string $field, string $named) { + $parsed = AccountInput::parse(cloud_account_input($override), 0, Provider::released()); + + expect($parsed->account)->toBeNull() + ->and($parsed->errors)->toHaveKey($field) + ->and($parsed->errors[$field])->toStartWith($named . ':'); +})->with([ + 'empty name' => [['name' => ''], 'name', 'Name'], + 'control in name' => [['name' => "a\nb"], 'name', 'Name'], + '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'], + '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'], + 'negative ceiling' => [['monthly_ceiling' => '-1'], 'monthly_ceiling', 'Monthly Ceiling'], + 'text ceiling' => [['monthly_ceiling' => 'lots'], 'monthly_ceiling', 'Monthly Ceiling'], +]); + +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'); + } +}); + +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]; + } + + $good_input = cloud_account_input(['provider' => $provider, 'scope_' . $field => $good] + $fields); + $bad_input = cloud_account_input(['provider' => $provider, 'scope_' . $field => $bad] + $fields); + + 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) . ':'); +})->with([ + ['aws', 'account_id', '123456789012', '12345678901/'], + ['aws', 'regions', 'us-east-1, us-gov-west-1', 'us-east-1,evil.example.com'], + ['gcp', 'project', 'my-project-1', 'my_project'], + ['azure', 'tenant', '0f8fad5b-d9cb-469f-a165-70867728950e', '0f8fad5b'], + ['azure', 'subscription', '7c9e6679-7425-40de-944b-e07fc1f90ae7', '../subscriptions'], + ['azure', 'regions', 'eastus,westeurope', 'east us/../x'], +]); + +it('pins fromRow on empty, NULL, and malformed values', function () { + $row = [ + 'id' => '7', + 'provider' => 'digitalocean', + 'name' => null, + 'poller_id' => '', + 'scope' => 'not json', + 'credential_source' => 'file', + 'credential_file' => ' /etc/cacti/do.token ', + 'collect_interval' => '10', + 'discover_interval' => 'x', + 'request_share' => '500', + 'monthly_ceiling' => '-3', + 'admin_state' => 'on', + 'verify_status' => 'bogus', + 'verified_at' => '-1', + ]; + + $account = Account::fromRow($row); + + expect($account)->not->toBeNull() + ->and($account->name)->toBe('') + ->and($account->pollerId)->toBe(Account::MAIN_POLLER) + ->and($account->scope)->toBe([]) + ->and($account->credentialSource)->toBe(CredentialSource::File) + ->and($account->credentialFile)->toBe('/etc/cacti/do.token') + ->and($account->collectInterval)->toBe(AccountInput::DEFAULT_COLLECT) + ->and($account->discoverInterval)->toBe(AccountInput::DEFAULT_DISCOVER) + ->and($account->requestShare)->toBe(100) + ->and($account->monthlyCeiling)->toBeNull() + ->and($account->adminState)->toBe(AdminState::Disabled) + ->and($account->verifyStatus)->toBe(VerifyStatus::Never) + ->and($account->verifiedAt)->toBe(0); +}); + +it('rejects rows that cannot be accounts', function (array $row) { + expect(Account::fromRow($row))->toBeNull(); +})->with([ + [['id' => '', 'provider' => 'aws', 'credential_source' => 'vault']], + [['id' => '0', 'provider' => 'aws', 'credential_source' => 'vault']], + [['id' => '1', 'provider' => 'oracle', 'credential_source' => 'vault']], + [['id' => '1', 'provider' => 'aws', 'credential_source' => null]], +]); + +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'])]); + + expect($account?->scope)->toBe(['account_id' => '123456789012']); +}); + +it('round-trips through toRow and fromRow', function () { + $account = AccountInput::parse(cloud_account_input(['monthly_ceiling' => '12.5']), 0, Provider::released())->account; + $again = Account::fromRow(['id' => 3] + $account->toRow()); + + expect($again->toRow())->toBe($account->toRow()); +}); + +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; + + expect($after->changedFields($before))->toBe(['name', 'collect_interval']) + ->and($before->changedFields(null))->toBe(array_keys($before->toRow())); +}); + +it('maps every error class to a fixed verify message', function () { + foreach (\Somethingwithproof\Cloud\ErrorClass::cases() as $error) { + $status = VerifyStatus::fromError($error); + + expect($status)->not->toBe(VerifyStatus::Ok) + ->and($status->message())->not->toBe(''); + } + + expect(VerifyStatus::fromError(\Somethingwithproof\Cloud\ErrorClass::Auth))->toBe(VerifyStatus::Invalid) + ->and(VerifyStatus::fromError(\Somethingwithproof\Cloud\ErrorClass::Permission))->toBe(VerifyStatus::Permission) + ->and(VerifyStatus::fromError(\Somethingwithproof\Cloud\ErrorClass::Transient))->toBe(VerifyStatus::Unreachable); +}); + +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_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']); + + $GLOBALS['__cloud_db_rows'] = []; + $GLOBALS['__cloud_in_tx'] = []; + + return [$deleted, $log]; +} + +it('deletes an account and its data in one transaction, then audits it', function () { + [$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']); +}); + +it('reruns the whole delete when InnoDB ends the transaction partway', function () { + // The third statement's transaction is gone, as after a deadlock. + [$deleted, $log] = cloud_delete_with([1, 1, 0, 0]); + + 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']); +}); + +it('gives up without auditing when every attempt loses its transaction', function () { + [$deleted, $log] = cloud_delete_with(array_fill(0, 12, 0)); + + expect($deleted)->toBeFalse() + ->and($log)->not->toContain('COMMIT') + ->and($log)->not->toContain('plugin_cloud_audit') + ->and(array_count_values($log)['BEGIN'])->toBe(3); +}); diff --git a/tests/Unit/BootTest.php b/tests/Unit/BootTest.php new file mode 100644 index 0000000..0ee49d6 --- /dev/null +++ b/tests/Unit/BootTest.php @@ -0,0 +1,64 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +use Somethingwithproof\Cloud\Log; + +beforeEach(function () { + $GLOBALS['__cloud_log'] = []; +}); + +it('reads its metadata from INFO', function () { + $info = plugin_cloud_version(); + + expect($info['name'])->toBe('cloud') + ->and($info['compat'])->toBe('1.2.31') + ->and($info['capabilities'])->toContain('remote_collect:1') + ->and($info['capabilities'])->not->toContain('remote_poller'); +}); + +it('boots and loads plugin classes on a supported runtime', function () { + expect(cloud_php_supported())->toBeTrue() + ->and(cloud_missing_extensions())->toBe([]) + ->and(cloud_boot())->toBeTrue() + ->and(class_exists(Log::class))->toBeTrue(); +}); + +it('does not refuse or log on a supported runtime', function () { + expect(cloud_refuse_unsupported())->toBeFalse() + ->and($GLOBALS['__cloud_log'])->toBe([]); +}); + +it('ignores classes outside its namespace and nested names', function () { + expect(class_exists('Somethingwithproof\\Cloud\\Nested\\Log'))->toBeFalse() + ->and(class_exists('Somethingwithproof\\CloudLog'))->toBeFalse(); +}); + +it('logs under the CLOUD tag at the right verbosity', function () { + Log::debug('d'); + Log::info('i'); + Log::warning('w'); + Log::error('e'); + + expect($GLOBALS['__cloud_log'])->toBe([ + ['message' => 'DEBUG: d', 'environ' => 'CLOUD', 'level' => POLLER_VERBOSITY_DEBUG], + ['message' => 'NOTE: i', 'environ' => 'CLOUD', 'level' => POLLER_VERBOSITY_MEDIUM], + ['message' => 'WARNING: w', 'environ' => 'CLOUD', 'level' => ''], + ['message' => 'ERROR: e', 'environ' => 'CLOUD', 'level' => ''], + ]); +}); diff --git a/tests/Unit/DriverContractTest.php b/tests/Unit/DriverContractTest.php new file mode 100644 index 0000000..bf328cc --- /dev/null +++ b/tests/Unit/DriverContractTest.php @@ -0,0 +1,221 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +use Somethingwithproof\Cloud\Account; +use Somethingwithproof\Cloud\AccountRepository; +use Somethingwithproof\Cloud\CollectResult; +use Somethingwithproof\Cloud\CredentialStore; +use Somethingwithproof\Cloud\DriverError; +use Somethingwithproof\Cloud\Drivers; +use Somethingwithproof\Cloud\ErrorClass; +use Somethingwithproof\Cloud\FixedClock; +use Somethingwithproof\Cloud\HttpRequest; +use Somethingwithproof\Cloud\HttpResponse; +use Somethingwithproof\Cloud\HttpTransport; +use Somethingwithproof\Cloud\Inventory; +use Somethingwithproof\Cloud\Operation; +use Somethingwithproof\Cloud\OutboundPolicy; +use Somethingwithproof\Cloud\Provider; +use Somethingwithproof\Cloud\ProviderDriver; +use Somethingwithproof\Cloud\SecretRepository; +use Somethingwithproof\Cloud\Secret; +use Somethingwithproof\Cloud\TransportError; +use Somethingwithproof\Cloud\UsageEstimate; +use Somethingwithproof\Cloud\Verifier; +use Somethingwithproof\Cloud\VerifyStatus; + +/** + * A driver that answers Verify from a canned HTTP status, the way a real one + * maps provider responses, and that would happily build a write request if + * asked, so the test proves the guard refuses it. + */ +final class FakeDriver implements ProviderDriver { + public function __construct(private readonly HttpTransport $http) { + } + + public function provider(): Provider { + return Provider::DigitalOcean; + } + + public function endpoints(Account $account): OutboundPolicy { + return new OutboundPolicy(['api.example.com']); + } + + public function operations(): array { + return [new Operation('Account', 'GET', 'api.example.com', '#^/v2/account$#')]; + } + + 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; + } catch (TransportError $e) { + throw DriverError::fromTransport($e); + } + + return match (true) { + $status === 200 => VerifyStatus::Ok, + $status === 401 => VerifyStatus::Invalid, + $status === 403 => VerifyStatus::Permission, + default => VerifyStatus::Malformed, + }; + } + + public function discover(Account $account, Secret $credential): Inventory { + $this->http->send(new HttpRequest('DELETE', 'https://api.example.com/v2/droplets/1')); + + return new Inventory([], 1); + } + + public function collect(Account $account, Secret $credential, array $requests): CollectResult { + return new CollectResult([], 0); + } + + public function estimate(array $requests, int $intervalSeconds): UsageEstimate { + return new UsageEstimate(count($requests), count($requests) * intdiv(2592000, max(1, $intervalSeconds)), 0.0); + } +} + +/** + * Stands in for SocketTransport behind the guard: replies with a status, or + * fails as an unreachable network would. + */ +function cloud_canned(?int $status): Closure { + return static fn (OutboundPolicy $policy): HttpTransport => new class ($status, $policy) implements HttpTransport { + public function __construct(private readonly ?int $status, private readonly OutboundPolicy $policy) { + } + + public function send(HttpRequest $request): HttpResponse { + $this->policy->check($request->url); + + if ($this->status === null) { + throw new TransportError('connect_timeout'); + } + + return new HttpResponse($this->status, [], ''); + } + }; +} + +function cloud_verify_with(?int $status, string $source = 'file'): VerifyStatus { + $dir = sys_get_temp_dir() . '/cloud-verify-' . bin2hex(random_bytes(4)); + mkdir($dir, 0700); + 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']); + $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)); + $result = $verifier->verify($account, 1); + + unlink($dir . '/token'); + rmdir($dir); + + return $result; +} + +beforeEach(function () { + $GLOBALS['__cloud_db_exec'] = []; +}); + +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]; + + expect($update['sql'])->toContain('UPDATE plugin_cloud_account SET verify_status') + ->and($update['params'][0])->toBe($expected->value); +})->with([ + 'valid' => [200, VerifyStatus::Ok], + 'expired' => [401, VerifyStatus::Invalid], + 'under-scoped' => [403, VerifyStatus::Permission], + 'unreachable' => [null, VerifyStatus::Unreachable], +]); + +it('reports a configuration status when the credential cannot be read', function () { + expect(cloud_verify_with(200, 'vault'))->toBe(VerifyStatus::Config); +}); + +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)); + + expect($verifier->verify($account, 1))->toBe(VerifyStatus::Config); +}); + +it('reports a configuration status, and no exception text, when a driver fails unexpectedly', function () { + $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')); + $clock = new FixedClock(1); + $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'); +}); + +it('refuses resource identities that do not fit or hold control characters, and trims display fields', function () { + $long = new \Somethingwithproof\Cloud\CloudResource('droplet', 'd1', str_repeat('n', 300), str_repeat('r', 80)); + + 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', "d1\nd2", 'x'))->toThrow(DriverError::class) + ->and(fn () => new \Somethingwithproof\Cloud\CloudResource('droplet', '', 'x'))->toThrow(DriverError::class); +}); + +it('wires drivers to a transport that refuses operations off their list', function () { + $drivers = new Drivers(cloud_canned(200)); + $drivers->register(Provider::DigitalOcean, static fn (HttpTransport $http): ProviderDriver => new FakeDriver($http)); + $account = Account::fromRow(['id' => 9, 'provider' => 'digitalocean', 'credential_source' => 'vault']); + + $driver = $drivers->for($account); + + expect(fn () => $driver->discover($account, new Secret('x')))->toThrow(TransportError::class, 'operation_refused'); +}); + +it('lists only read operations for every registered driver', function () { + // The production registry; each provider phase adds its driver here. + $drivers = Drivers::production(); + + foreach (Provider::cases() as $provider) { + $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); + } + } + + expect(true)->toBeTrue(); +}); + +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) { + expect((new TransportError($kind))->errorClass())->toBeInstanceOf(ErrorClass::class); + } + + expect((new TransportError('total_timeout'))->errorClass())->toBe(ErrorClass::Transient) + ->and((new TransportError('host_refused'))->errorClass())->toBe(ErrorClass::Config) + ->and((new TransportError('too_large'))->errorClass())->toBe(ErrorClass::Malformed); +}); diff --git a/tests/Unit/FreshnessTest.php b/tests/Unit/FreshnessTest.php new file mode 100644 index 0000000..9027324 --- /dev/null +++ b/tests/Unit/FreshnessTest.php @@ -0,0 +1,71 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +use Somethingwithproof\Cloud\FixedClock; +use Somethingwithproof\Cloud\Freshness; +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) { + $now = 1_800_000_000; + $fresh = new FreshnessEvaluator(new FixedClock($now)); + + // Window: 60 s period + 120 s delay + 300 s interval = 480 s. + expect($fresh->evaluate(new Observation(1, 'cpu', 1.0, $now - $age, $now), 60, 120, 300))->toBe($expected); +})->with([ + [0, Freshness::Current], + [480, Freshness::Current], + [481, Freshness::Delayed], + [960, Freshness::Delayed], + [961, Freshness::Stale], + [-120, Freshness::Current], + [-121, Freshness::ClockSkew], +]); + +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); +}); + +it('reports never-observed series as never, and only current or delayed as usable', function () { + $fresh = new FreshnessEvaluator(new FixedClock(100)); + + expect($fresh->evaluate(null, 60, 0, 300))->toBe(Freshness::Never) + ->and($fresh->evaluate(new Observation(1, 'cpu', null, 0, 100), 60, 0, 300))->toBe(Freshness::Never) + ->and(array_map(fn (Freshness $f) => $f->usable(), Freshness::cases()))->toBe([true, true, false, false, false]); +}); + +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'])) + ->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' => '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']); + + expect($health->collection)->toBe(\Somethingwithproof\Cloud\CollectionState::Never) + ->and($health->error)->toBeNull() + ->and($health->runDuration)->toBe(0.0) + ->and(\Somethingwithproof\Cloud\AccountHealth::fromRow(['account_id' => '']))->toBeNull(); +}); diff --git a/tests/Unit/HealthWarningsTest.php b/tests/Unit/HealthWarningsTest.php new file mode 100644 index 0000000..f8a22de --- /dev/null +++ b/tests/Unit/HealthWarningsTest.php @@ -0,0 +1,115 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +use Somethingwithproof\Cloud\Account; +use Somethingwithproof\Cloud\HealthWarnings; +use Somethingwithproof\Cloud\Settings; + +/* + * Each health warning from a file or settings fixture (#37), through the + * production checks. + */ + +beforeEach(function () { + $this->dir = sys_get_temp_dir() . '/cloud-warn-' . bin2hex(random_bytes(4)); + mkdir($this->dir, 0700); + $this->key = $this->dir . '/vault.key'; + file_put_contents($this->key, bin2hex(random_bytes(32))); + chmod($this->key, 0600); + $this->token = $this->dir . '/token'; + file_put_contents($this->token, 'dop_v1_' . str_repeat('a', 64)); + chmod($this->token, 0600); +}); + +afterEach(function () { + foreach (glob($this->dir . '/*') ?: [] as $path) { + unlink($path); + } + + rmdir($this->dir); +}); + +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']); +} + +function cloud_warnings(string $key, array $accounts, int $poller = 300): array { + return HealthWarnings::production()->for(Settings::fromRow(['cloud_vault_key_file' => $key]), $accounts, $poller); +} + +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([]); +}); + +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), + }; + + $warnings = cloud_warnings($path, [cloud_warn_account()]); + + expect($warnings)->toHaveCount(1) + ->and($warnings[0]['admin'])->toBeFalse() + ->and($warnings[0]['message'])->toStartWith('The vault key file cannot be used:') + ->and($warnings[0]['message'])->toContain($reason); +})->with([ + ['missing', 'does not exist'], + ['shared', 'other users'], + ['short', '32 bytes or 64 hexadecimal'], +]); + +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), + }; + + $warnings = cloud_warnings($this->key, [cloud_warn_account(['credential_source' => 'file', 'credential_file' => $path])]); + + expect($warnings)->toHaveCount(1) + ->and($warnings[0]['admin'])->toBeTrue() + ->and($warnings[0]['message'])->toStartWith('Ops: the credential file cannot be used:') + ->and($warnings[0]['message'])->toContain($reason) + ->and($warnings[0]['message'])->not->toContain($this->dir); +})->with([ + ['missing', 'does not exist'], + ['shared', 'other users'], + ['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]); +})->with([ + [300, 300, null], + [600, 300, null], + [60, 60, null], + [120, 300, 'is shorter than the poller interval of 300 seconds, so it is collected every 300 seconds.'], + [450, 300, 'is not a multiple of the poller interval of 300 seconds, so it is collected every 600 seconds.'], + // Within the collector's slack of a poller cycle, so due on that cycle. + [310, 300, 'is not a multiple of the poller interval of 300 seconds, so it is collected every 300 seconds.'], +]); + +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([]); +}); diff --git a/tests/Unit/LifecycleUnitTest.php b/tests/Unit/LifecycleUnitTest.php new file mode 100644 index 0000000..b91d380 --- /dev/null +++ b/tests/Unit/LifecycleUnitTest.php @@ -0,0 +1,111 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +use Somethingwithproof\Cloud\Pages; +use Somethingwithproof\Cloud\Schema; +use Somethingwithproof\Cloud\Settings; + +it('applies documented defaults to settings that were never saved', function () { + $settings = Settings::fromRow([]); + + expect($settings->vaultKeyFile)->toBe(Settings::DEFAULT_KEY_FILE) + ->and($settings->collectorBudget)->toBe(Settings::DEFAULT_BUDGET) + ->and($settings->keepTablesOnUninstall)->toBeTrue(); +}); + +it('drops tables on uninstall only after the box was cleared and saved', function () { + expect(Settings::fromRow(['cloud_uninstall_keep_tables' => ''])->keepTablesOnUninstall)->toBeFalse() + ->and(Settings::fromRow(['cloud_uninstall_keep_tables' => null])->keepTablesOnUninstall)->toBeFalse() + ->and(Settings::fromRow(['cloud_uninstall_keep_tables' => 'on'])->keepTablesOnUninstall)->toBeTrue(); +}); + +it('bounds the collector budget', function (mixed $stored, int $expected) { + expect(Settings::fromRow(['cloud_collector_budget' => $stored])->collectorBudget)->toBe($expected); +})->with([ + ['120', 120], + ['9', Settings::DEFAULT_BUDGET], + ['-5', Settings::DEFAULT_BUDGET], + ['abc', Settings::DEFAULT_BUDGET], + ['', Settings::DEFAULT_BUDGET], + ['99999', 3600], +]); + +it('gives every setting in the form a default that fromRow agrees with', function () { + $form = Settings::form(); + + foreach (Settings::NAMES as $name) { + expect($form)->toHaveKey($name); + } + + $defaults = Settings::fromRow([ + 'cloud_vault_key_file' => $form['cloud_vault_key_file']['default'], + 'cloud_collector_budget' => $form['cloud_collector_budget']['default'], + 'cloud_uninstall_keep_tables' => $form['cloud_uninstall_keep_tables']['default'], + ]); + + expect($defaults)->toEqual(Settings::fromRow([])); +}); + +it('puts every page in exactly one realm', function () { + $files = Pages::files(); + + expect($files)->toBe(array_values(array_unique($files))); + + foreach (Pages::realms() as $realm) { + expect($realm['files'])->not->toBe([]); + } +}); + +it('lists every page script the plugin ships in a realm', function () { + $root = dirname(__DIR__, 2); + $scripts = array_map('basename', glob($root . '/cloud*.php')); + + expect(Pages::files())->not->toBeEmpty(); + + foreach ($scripts as $script) { + expect(in_array($script, Pages::files(), true))->toBeTrue($script); + } +}); + +it('gives every menu page a breadcrumb under the console', function () { + $nav = Pages::navigation(); + + foreach (array_keys(Pages::menu()) as $file) { + expect($nav[$file . ':']['mapping'])->toBe('index.php:') + ->and($nav[$file . ':']['url'])->toBe($file); + } +}); + +it('names every hook function that setup.php defines', function () { + foreach (Schema::HOOKS as $function) { + expect(function_exists($function))->toBeTrue($function); + } +}); + +it('defines plugin tables with the plugin prefix, a primary key, and no secret columns in the clear', function () { + foreach (Schema::tables() as $table => $definition) { + expect($table)->toStartWith('plugin_cloud_') + ->and($definition)->toHaveKey('primary') + ->and($definition['type'])->toBe('InnoDB'); + + foreach ($definition['columns'] as $column) { + expect($column['name'])->not->toMatch('/token|password|secret|private_key/'); + } + } +}); diff --git a/tests/Unit/RowTest.php b/tests/Unit/RowTest.php new file mode 100644 index 0000000..979c71c --- /dev/null +++ b/tests/Unit/RowTest.php @@ -0,0 +1,108 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + + +use Somethingwithproof\Cloud\Row; + +describe('Row::int', function () { + it('reads whole decimal numbers from strings and ints', function () { + expect(Row::int(['v' => '42'], 'v'))->toBe(42) + ->and(Row::int(['v' => ' 7 '], 'v'))->toBe(7) + ->and(Row::int(['v' => '-3'], 'v'))->toBe(-3) + ->and(Row::int(['v' => 9], 'v'))->toBe(9); + }); + + it('returns the default for missing, NULL, and empty values', function () { + expect(Row::int([], 'v', 5))->toBe(5) + ->and(Row::int(['v' => null], 'v', 5))->toBe(5) + ->and(Row::int(['v' => ''], 'v', 5))->toBe(5); + }); + + it('returns the default for malformed values instead of truncating them', function (mixed $value) { + expect(Row::int(['v' => $value], 'v', 5))->toBe(5); + })->with([ + 'decimal' => '1.5', + 'exponent' => '1e3', + 'trailing text' => '12abc', + 'leading text' => 'abc12', + 'float' => 3.0, + 'bool' => true, + 'array' => [[1]], + 'too long' => '1234567890123456789012', + ]); + + it('returns the default below the minimum', function () { + expect(Row::int(['v' => '0'], 'v', 1, 1))->toBe(1) + ->and(Row::int(['v' => '-1'], 'v', 0, 0))->toBe(0) + ->and(Row::int(['v' => '1'], 'v', 9, 1))->toBe(1); + }); +}); + +describe('Row::float', function () { + it('keeps zero distinct from unknown', function () { + expect(Row::float(['v' => '0'], 'v'))->toBe(0.0) + ->and(Row::float(['v' => 0], 'v'))->toBe(0.0) + ->and(Row::float(['v' => null], 'v'))->toBeNull() + ->and(Row::float(['v' => ''], 'v'))->toBeNull() + ->and(Row::float([], 'v'))->toBeNull(); + }); + + it('reads numeric strings including rrdtool exponent notation', function () { + expect(Row::float(['v' => '1.2345000000e-02'], 'v'))->toBe(0.012345) + ->and(Row::float(['v' => ' 20 '], 'v'))->toBe(20.0); + }); + + it('treats rrdtool unknowns and malformed text as unknown', function (mixed $value) { + expect(Row::float(['v' => $value], 'v'))->toBeNull(); + })->with(['U', 'nan', 'NaN', 'inf', '-', '1,5', 'abc', [[1]], true]); + + it('treats non-finite floats as unknown', function () { + expect(Row::float(['v' => NAN], 'v'))->toBeNull() + ->and(Row::float(['v' => INF], 'v'))->toBeNull(); + }); +}); + +describe('Row::string', function () { + it('casts scalars, trims, and maps missing or NULL to empty', function () { + expect(Row::string(['v' => ' a '], 'v'))->toBe('a') + ->and(Row::string(['v' => 12], 'v'))->toBe('12') + ->and(Row::string(['v' => null], 'v'))->toBe('') + ->and(Row::string([], 'v'))->toBe('') + ->and(Row::string(['v' => ['x']], 'v'))->toBe(''); + }); +}); + +describe('Row::bool', function () { + it('accepts only explicit true spellings', function (mixed $value, bool $expected) { + expect(Row::bool(['v' => $value], 'v'))->toBe($expected); + })->with([ + 'checkbox on' => ['on', true], + 'yes' => ['yes', true], + 'YES' => [' YES ', true], + 'one string' => ['1', true], + 'one int' => [1, true], + 'true' => [true, true], + 'empty' => ['', false], + 'null' => [null, false], + 'zero' => ['0', false], + 'off' => ['off', false], + 'two' => [2, false], + 'garbage' => ['enabled', false], + ]); +}); diff --git a/tests/Unit/VaultTest.php b/tests/Unit/VaultTest.php new file mode 100644 index 0000000..903ef80 --- /dev/null +++ b/tests/Unit/VaultTest.php @@ -0,0 +1,278 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +use Somethingwithproof\Cloud\CredentialError; +use Somethingwithproof\Cloud\CredentialFile; +use Somethingwithproof\Cloud\Redactor; +use Somethingwithproof\Cloud\Secret; +use Somethingwithproof\Cloud\Vault; +use Somethingwithproof\Cloud\VaultEntry; +use Somethingwithproof\Cloud\VaultKey; + +const CLOUD_TEST_SECRET = 'dop_v1_0123456789abcdef0123456789abcdef0123456789abcdef0123456789ab'; + +beforeEach(function () { + $this->dir = sys_get_temp_dir() . '/cloud-vault-' . bin2hex(random_bytes(4)); + mkdir($this->dir, 0700); +}); + +afterEach(function () { + foreach (glob($this->dir . '/{,.}*', GLOB_BRACE) ?: [] as $path) { + if (is_link($path) || is_file($path)) { + unlink($path); + } elseif (is_dir($path) && !in_array(basename($path), ['.', '..'], true)) { + rmdir($path); + } + } + + rmdir($this->dir); +}); + +function cloud_file(string $dir, string $name, string $content, int $mode = 0600): string { + $path = $dir . '/' . $name; + file_put_contents($path, $content); + chmod($path, $mode); + + return $path; +} + +function cloud_refusal(callable $read): string { + try { + $read(); + } catch (CredentialError $e) { + return $e->getMessage(); + } + + return 'accepted'; +} + +it('round-trips a secret through AES-256-GCM with a fresh nonce each time', function () { + $vault = new Vault(VaultKey::fromBytes(random_bytes(32))); + $one = $vault->encrypt(new Secret(CLOUD_TEST_SECRET), 5, 'credential'); + $two = $vault->encrypt(new Secret(CLOUD_TEST_SECRET), 5, 'credential'); + + expect($vault->decrypt($one, 5, 'credential')->reveal())->toBe(CLOUD_TEST_SECRET) + ->and(strlen($one->nonce))->toBe(Vault::NONCE_BYTES) + ->and($one->nonce)->not->toBe($two->nonce) + ->and($one->ciphertext)->not->toContain(CLOUD_TEST_SECRET); +}); + +it('binds a ciphertext to its account and purpose', function () { + $vault = new Vault(VaultKey::fromBytes(random_bytes(32))); + $entry = $vault->encrypt(new Secret(CLOUD_TEST_SECRET), 5, 'credential'); + + expect(cloud_refusal(fn () => $vault->decrypt($entry, 6, 'credential')))->toContain('integrity') + ->and(cloud_refusal(fn () => $vault->decrypt($entry, 5, 'token')))->toContain('integrity'); +}); + +it('detects a tampered ciphertext or tag', function () { + $vault = new Vault(VaultKey::fromBytes(random_bytes(32))); + $entry = $vault->encrypt(new Secret(CLOUD_TEST_SECRET), 5, 'credential'); + + $flipped = new VaultEntry($entry->nonce, $entry->ciphertext ^ "\x01", $entry->tag, $entry->keyId); + $badTag = new VaultEntry($entry->nonce, $entry->ciphertext, str_repeat("\0", 16), $entry->keyId); + + expect(cloud_refusal(fn () => $vault->decrypt($flipped, 5, 'credential')))->toContain('integrity') + ->and(cloud_refusal(fn () => $vault->decrypt($badTag, 5, 'credential')))->toContain('integrity'); +}); + +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'); +}); + +it('reads a key file of 32 raw bytes or 64 hex characters', function () { + $bytes = random_bytes(32); + + expect(VaultKey::fromFile(cloud_file($this->dir, 'raw', $bytes))->bytes())->toBe($bytes) + ->and(VaultKey::fromFile(cloud_file($this->dir, 'hex', bin2hex($bytes) . "\n"))->bytes())->toBe($bytes) + ->and(VaultKey::fromFile(cloud_file($this->dir, 'hex0640', bin2hex($bytes), 0640))->bytes())->toBe($bytes); +}); + +it('refuses key files that fail a check, naming the check', function (string $case, string $reason) { + $dir = $this->dir; + + $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'; })(), + '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)), + 'long' => cloud_file($dir, 'long', random_bytes(33)), + 'not hex' => cloud_file($dir, 'nothex', str_repeat('g', 64)), + 'oversize' => cloud_file($dir, 'big', str_repeat('a', 100)), + }; + + expect(cloud_refusal(fn () => VaultKey::fromFile($path)))->toContain($reason); +})->with([ + ['relative', 'absolute path'], + ['missing', 'does not exist'], + ['symlink', 'symbolic link'], + ['directory', 'not a regular file'], + ['world-read', 'other users'], + ['world-write', 'other users'], + ['short', '32 bytes or 64 hexadecimal'], + ['long', '32 bytes or 64 hexadecimal'], + ['not hex', '32 bytes or 64 hexadecimal'], + ['oversize', 'larger than allowed'], +]); + +it('refuses credential files that fail a check', function () { + $dir = $this->dir; + symlink(cloud_file($dir, 'real', CLOUD_TEST_SECRET), $dir . '/link'); + + expect(CredentialFile::read(cloud_file($dir, 'ok', CLOUD_TEST_SECRET . "\n"))->reveal())->toBe(CLOUD_TEST_SECRET) + ->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, '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'); +}); + +it('never puts secret material in a refusal message', function () { + $path = cloud_file($this->dir, 'k', CLOUD_TEST_SECRET); + + expect(cloud_refusal(fn () => VaultKey::fromFile($path)))->not->toContain(CLOUD_TEST_SECRET); +}); + +it('hides secrets from dumps and refuses to serialize or export them', function () { + $secret = new Secret(CLOUD_TEST_SECRET); + $key = VaultKey::fromBytes(str_repeat('k', 32)); + + ob_start(); + var_dump($secret, $key); + $dumped = (string) ob_get_clean(); + + expect($dumped . print_r($secret, true) . print_r($key, true))->not->toContain(CLOUD_TEST_SECRET) + ->and($dumped)->not->toContain(str_repeat('k', 32)) + ->and(fn () => serialize($secret))->toThrow(LogicException::class) + ->and(fn () => serialize($key))->toThrow(LogicException::class) + ->and(fn () => json_encode(['s' => $secret], JSON_THROW_ON_ERROR))->not->toThrow(Throwable::class) + ->and(json_encode(['s' => $secret]))->not->toContain(CLOUD_TEST_SECRET); +}); + +it('keeps secrets out of exception traces', function () { + $trace = ''; + + try { + (static function (Secret $s, string $raw) { + throw new RuntimeException('boom'); + })(new Secret(CLOUD_TEST_SECRET), 'x'); + } catch (RuntimeException $e) { + $trace = $e->getTraceAsString(); + } + + expect($trace)->not->toContain(CLOUD_TEST_SECRET); +}); + +it('redacts known secrets in every encoding and authorization material by pattern', function () { + $redactor = new Redactor(); + $redactor->add(new Secret('p@ss/word+with spaces')); + $redactor->add(new Secret(CLOUD_TEST_SECRET)); + + $text = implode("\n", [ + 'token ' . CLOUD_TEST_SECRET, + 'url ?key=' . rawurlencode('p@ss/word+with spaces') . '&x=' . urlencode('p@ss/word+with spaces'), + 'json ' . json_encode(['v' => 'p@ss/word+with spaces']), + 'Authorization: AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20261114, Signature=abc123', + 'header Bearer eyJhbGciOi.payload.sig', + 'query X-Amz-Signature=deadbeef&X-Amz-Credential=AKID%2F2026', + 'body {"access_token":"ya29.a0Af","expires_in":3599}', + "-----BEGIN PRIVATE KEY-----\nMIIEv\n-----END PRIVATE KEY-----", + ]); + + $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) { + expect($clean)->not->toContain($leak); + } + + expect($clean)->toContain('expires_in'); +}); + +it('masks every accepted credential, however short', function () { + $redactor = new Redactor(); + $redactor->add(new Secret('s3cr3t!')); + $redactor->add(new Secret('')); + + expect($redactor->clean('credential rejected: s3cr3t!'))->toBe('credential rejected: [redacted]'); +}); + +it('masks header values even when a known secret is part of the header name', function () { + $redactor = new Redactor(); + $redactor->add(new Secret('auth')); + + expect($redactor->clean('authorization: fresh-secret-123'))->not->toContain('fresh-secret-123') + ->and($redactor->clean('token auth failed'))->toBe('token [redacted] failed'); +}); + +it('masks a known secret whole when a pattern covers only part of it', function () { + $redactor = new Redactor(); + $redactor->add(new Secret('first-half second-half')); + + $clean = $redactor->clean("Bearer first-half second-half\naccess_token=first-half second-half&x=1\nsignature=&y=2"); + + expect($clean)->not->toContain('first-half') + ->and($clean)->not->toContain('second-half') + ->and($clean)->toContain('signature=[redacted]&y=2') + ->and($clean)->toContain('&x=1'); +}); + +it('keeps secrets out of var_export, including inside a vault key', function () { + $secret = new Secret('example-token-value'); + $key = VaultKey::fromBytes(str_repeat('k', 32)); + + expect(var_export($secret, true))->not->toContain('example-token-value') + ->and(var_export($key, true))->not->toContain(str_repeat('k', 32)) + ->and(print_r($secret, true))->not->toContain('example-token-value') + ->and($secret->reveal())->toBe('example-token-value') + ->and(fn () => clone $secret)->toThrow(LogicException::class); +}); + +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); + + if (!$made) { + $this->markTestSkipped('posix_mkfifo is not available'); + } + + try { + expect(cloud_refusal(fn () => VaultKey::fromFile($fifo)))->toContain('not a regular file'); + } finally { + unlink($fifo); + } +}); + +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)) + ->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() + ->and(VaultEntry::fromRow(['nonce' => 12] + $row))->toBeNull() + ->and(VaultEntry::fromRow([]))->toBeNull(); +}); diff --git a/tests/bin/collector-flow.php b/tests/bin/collector-flow.php new file mode 100644 index 0000000..5df1be6 --- /dev/null +++ b/tests/bin/collector-flow.php @@ -0,0 +1,220 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Collector scenarios against a real Cacti database, included by + * tests/bin/lifecycle.php collector_flow. A fake driver stands in for a + * provider; everything else is the production code. Sets $result. + */ + +use Somethingwithproof\Cloud\Account; +use Somethingwithproof\Cloud\CloudResource; +use Somethingwithproof\Cloud\CollectResult; +use Somethingwithproof\Cloud\Collector; +use Somethingwithproof\Cloud\CredentialStore; +use Somethingwithproof\Cloud\Drivers; +use Somethingwithproof\Cloud\FixedClock; +use Somethingwithproof\Cloud\HealthRepository; +use Somethingwithproof\Cloud\HttpTransport; +use Somethingwithproof\Cloud\Inventory; +use Somethingwithproof\Cloud\LeaseRepository; +use Somethingwithproof\Cloud\Observation; +use Somethingwithproof\Cloud\ObservationRepository; +use Somethingwithproof\Cloud\OutboundPolicy; +use Somethingwithproof\Cloud\Provider; +use Somethingwithproof\Cloud\ProviderDriver; +use Somethingwithproof\Cloud\Redactor; +use Somethingwithproof\Cloud\ResourceRepository; +use Somethingwithproof\Cloud\Secret; +use Somethingwithproof\Cloud\SecretRepository; +use Somethingwithproof\Cloud\SeriesRepository; +use Somethingwithproof\Cloud\UsageEstimate; +use Somethingwithproof\Cloud\VerifyStatus; + +include_once($config['base_path'] . '/plugins/cloud/setup.php'); +cloud_boot(); + +final class FlowDriver implements ProviderDriver { + /** @var list resource ids discovery returns */ + public static array $present = ['d1', 'd2']; + public static int $discoveries = 0; + /** @var list */ + public static array $collected = []; + public static int $observedAt = 0; + /** @var list account names in the order discovery ran */ + public static array $order = []; + public static ?FixedClock $clock = null; + /** seconds each discovery takes on $clock */ + public static int $tick = 0; + + public function __construct(HttpTransport $http) { + } + + public function provider(): Provider { + return Provider::DigitalOcean; + } + + public function endpoints(Account $account): OutboundPolicy { + return new OutboundPolicy(['api.example.com']); + } + + public function operations(): array { + return []; + } + + public function verify(Account $account, Secret $credential): VerifyStatus { + return VerifyStatus::Ok; + } + + public function discover(Account $account, Secret $credential): Inventory { + self::$discoveries++; + 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); + } + + public function collect(Account $account, Secret $credential, array $requests): CollectResult { + $out = []; + + foreach ($requests as $request) { + self::$collected[] = $request->providerId . '/' . $request->metric; + $out[] = new Observation($request->resourceId, $request->metric, 42.5, self::$observedAt, self::$observedAt + 30); + } + + return new CollectResult($out, count($requests)); + } + + public function estimate(array $requests, int $intervalSeconds): UsageEstimate { + return new UsageEstimate(0, 0, 0.0); + } +} + +$flow_dir = sys_get_temp_dir() . '/cloud-flow-' . getmypid(); +@mkdir($flow_dir, 0700); +file_put_contents($flow_dir . '/token', 'dop_v1_' . str_repeat('b', 64)); +chmod($flow_dir . '/token', 0600); + +$flow_clock = new FixedClock(1800000000); + +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)); + + return (int) db_fetch_insert_id(); +} + +function flow_collector($clock, $holder) { + $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( + new \Somethingwithproof\Cloud\AccountRepository(false, $clock), $drivers, + new CredentialStore(new SecretRepository(false, $clock), '/nonexistent'), + new LeaseRepository(false, $clock), new ResourceRepository(false, $clock), new SeriesRepository(false), + new ObservationRepository(false), new HealthRepository(false), new Redactor(), $clock, $holder + ); +} + +$main = flow_account('Main', 1, 'enabled'); +$remote = flow_account('Remote', 2, 'enabled'); +$disabled = flow_account('Off', 1, 'disabled'); +$result = array(); + +// Run 1: discovery is due; no series are mapped yet, so nothing is read. +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)); + +// 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')); + +// Run 2 within the interval does nothing; run 3 after it collects. +$flow_clock->advance(60); +flow_collector($flow_clock, 'h2')->run(1, 240); +$result['collected_early'] = FlowDriver::$collected; + +$flow_clock->advance(300); +FlowDriver::$observedAt = $flow_clock->now() - 120; +flow_collector($flow_clock, 'h3')->run(1, 240); +$result['collected'] = FlowDriver::$collected; + +// A run a few seconds early, as poller start times drift, is still due; +// one well inside the interval is not. +$flow_clock->advance(200); +flow_collector($flow_clock, 'h3a')->run(1, 240); +$result['collected_at_200'] = count(FlowDriver::$collected); +$flow_clock->advance(96); +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)); + +// 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())); +(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')); + +// A lease held by another live run makes this run skip the account. +$flow_clock->advance(400); +$result['while_leased'] = flow_collector($flow_clock, 'h5')->run(1, 240); +(new LeaseRepository(false, $flow_clock))->release($main, 'h4'); + +// A zero budget stops before the first account. +$result['no_budget'] = flow_collector($flow_clock, 'h6')->run(1, 0); + +// Discovery without d2, three times past its interval: missing, then deleted. +FlowDriver::$present = array('d1'); +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)); +} + +// 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; + +// 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. +$second = flow_account('Second', 1, 'enabled'); +FlowDriver::$order = array(); +FlowDriver::$clock = $flow_clock; +FlowDriver::$tick = 300; +$flow_clock->advance(3700); +$result['order_run1'] = flow_collector($flow_clock, 'h8')->run(1, 100); +$flow_clock->advance(3700); +flow_collector($flow_clock, 'h9')->run(1, 100); +$result['order'] = FlowDriver::$order; +FlowDriver::$clock = null; + +db_execute('DELETE FROM data_template_data WHERE local_data_id IN (900001, 900002)'); +unlink($flow_dir . '/token'); +rmdir($flow_dir); diff --git a/tests/bin/collector-restart.php b/tests/bin/collector-restart.php new file mode 100644 index 0000000..4cb3e4f --- /dev/null +++ b/tests/bin/collector-restart.php @@ -0,0 +1,189 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Collector restart scenarios (#35), included by tests/bin/lifecycle.php: + * + * collector_kill a run killed mid-account leaves no partial result and + * the next run continues once the lease expires + * collector_victim the run that is killed (started by collector_kill) + * collector_second a second collector start exits at once + * + * Sets $result. Must parse on PHP 8.0 apart from the driver class, which + * only loads where the plugin boots. + */ + +use Somethingwithproof\Cloud\Account; +use Somethingwithproof\Cloud\CloudResource; +use Somethingwithproof\Cloud\CollectResult; +use Somethingwithproof\Cloud\Collector; +use Somethingwithproof\Cloud\CredentialStore; +use Somethingwithproof\Cloud\Drivers; +use Somethingwithproof\Cloud\FixedClock; +use Somethingwithproof\Cloud\HealthRepository; +use Somethingwithproof\Cloud\HttpTransport; +use Somethingwithproof\Cloud\Inventory; +use Somethingwithproof\Cloud\LeaseRepository; +use Somethingwithproof\Cloud\Observation; +use Somethingwithproof\Cloud\ObservationRepository; +use Somethingwithproof\Cloud\OutboundPolicy; +use Somethingwithproof\Cloud\Provider; +use Somethingwithproof\Cloud\ProviderDriver; +use Somethingwithproof\Cloud\Redactor; +use Somethingwithproof\Cloud\ResourceRepository; +use Somethingwithproof\Cloud\Secret; +use Somethingwithproof\Cloud\SecretRepository; +use Somethingwithproof\Cloud\SeriesRepository; +use Somethingwithproof\Cloud\UsageEstimate; +use Somethingwithproof\Cloud\VerifyStatus; + +include_once($config['base_path'] . '/plugins/cloud/setup.php'); +cloud_boot(); + +const RESTART_TIME = 1800000000; +const RESTART_BUDGET = 240; + +final class RestartDriver implements ProviderDriver { + public static bool $kill = false; + + public function __construct(HttpTransport $http) { + } + + public function provider(): Provider { + return Provider::DigitalOcean; + } + + public function endpoints(Account $account): OutboundPolicy { + return new OutboundPolicy(['api.example.com']); + } + + public function operations(): array { + return []; + } + + public function verify(Account $account, Secret $credential): VerifyStatus { + return VerifyStatus::Ok; + } + + public function discover(Account $account, Secret $credential): Inventory { + return new Inventory([new CloudResource('droplet', 'r1', 'Restart one', 'nyc3')], 1); + } + + public function collect(Account $account, Secret $credential, array $requests): CollectResult { + // Killed outright, as by the OOM killer or a reboot: no finally + // block runs, so the lease is never released. + if (self::$kill) { + function_exists('posix_kill') ? posix_kill(getmypid(), 9) : exec('kill -9 ' . getmypid()); + sleep(5); + } + + $out = []; + + foreach ($requests as $request) { + $out[] = new Observation($request->resourceId, $request->metric, 7.0, RESTART_TIME - 60, RESTART_TIME); + } + + return new CollectResult($out, 1); + } + + public function estimate(array $requests, int $intervalSeconds): UsageEstimate { + return new UsageEstimate(0, 0, 0.0); + } +} + +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)); + + return new Collector( + new \Somethingwithproof\Cloud\AccountRepository(false, $clock), $drivers, + new CredentialStore(new SecretRepository(false, $clock), '/nonexistent'), + new LeaseRepository(false, $clock), new ResourceRepository(false, $clock), new SeriesRepository(false), + new ObservationRepository(false), new HealthRepository(false), new Redactor(), $clock, $holder + ); +} + +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'), + ); +} + +$restart_token = sys_get_temp_dir() . '/cloud-restart.token'; + +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')"); + + // 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); + $status = proc_get_status($holder); + register_process('cloud', 'collector', 1, $status['pid'], 300); + $started = microtime(true); + exec(escapeshellarg(PHP_BINARY) . ' -q ' . escapeshellarg($script) . ' --poller=1 --force 2>&1', $lines, $rc); + 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')); + + // 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); + $result['leases_when_free'] = (int) db_fetch_cell('SELECT COUNT(*) FROM plugin_cloud_lease'); + + break; + case 'collector_victim': + RestartDriver::$kill = true; + restart_collector(new FixedClock(RESTART_TIME), 'victim')->run(1, RESTART_BUDGET); + + break; + 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)); + $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)); + $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); + $result = array('victim_rc' => $rc, 'after_kill' => restart_state($account)); + + // Inside the dead run's lease, the account is skipped, not doubled. + $clock = new FixedClock(RESTART_TIME + 60); + $result['while_leased'] = restart_collector($clock, 'next')->run(1, RESTART_BUDGET); + + // After it expires, the next run takes over and finishes the account. + $clock->advance(RESTART_BUDGET + 120); + $result['after_expiry'] = restart_collector($clock, 'next')->run(1, RESTART_BUDGET); + $result['final'] = restart_state($account); + + db_execute('DELETE FROM data_template_data WHERE local_data_id = 900101'); + unlink($restart_token); + + break; +} diff --git a/tests/bin/lifecycle.php b/tests/bin/lifecycle.php new file mode 100644 index 0000000..dfc25b3 --- /dev/null +++ b/tests/bin/lifecycle.php @@ -0,0 +1,220 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Drive the plugin lifecycle through Cacti's own plugin API in a fresh PHP + * process, the way plugins.php and cli/plugin_manage.php do, and print the + * resulting state as JSON. Used by tests/Integration. Disposable databases + * only. + * + * php plugins/cloud/tests/bin/lifecycle.php [argument] + */ + +chdir(dirname(__DIR__, 4)); + +require('./include/cli_check.php'); +require_once($config['base_path'] . '/lib/plugins.php'); +require_once($config['base_path'] . '/lib/poller.php'); + +if (getenv('CLOUD_TEST_DATABASE') !== 'disposable') { + fwrite(STDERR, "Set CLOUD_TEST_DATABASE=disposable\n"); + exit(2); +} + +$action = isset($argv[1]) ? $argv[1] : 'state'; +$argument = isset($argv[2]) ? $argv[2] : ''; +$result = null; + +ob_start(); + +switch ($action) { + 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) { + db_execute('DROP TABLE `' . $row['t'] . '`'); + } + + db_execute("DELETE FROM settings WHERE name LIKE 'cloud\\_%'"); + db_execute("DELETE FROM plugin_db_changes WHERE plugin = 'cloud'"); + + break; + case 'install': + api_plugin_install('cloud'); + + break; + case 'enable': + api_plugin_enable('cloud'); + + break; + case 'disable': + api_plugin_disable('cloud'); + + break; + case 'uninstall': + api_plugin_uninstall('cloud'); + + break; + case 'upgrade': + include_once($config['base_path'] . '/plugins/cloud/setup.php'); + $result = plugin_cloud_upgrade(); + + break; + case 'migrate_through': + // Stop after the given migration, as an upgrade killed part way would. + include_once($config['base_path'] . '/plugins/cloud/setup.php'); + cloud_boot(); + $result = (new \Somethingwithproof\Cloud\Schema(false))->migrate((int) $argument); + + break; + case 'set_version': + db_execute_prepared("UPDATE plugin_config SET version = ? WHERE directory = 'cloud'", array($argument)); + + break; + case 'set_schema': + db_execute_prepared("REPLACE INTO settings (name, value) VALUES ('cloud_schema_version', ?)", array($argument)); + + break; + case 'set_setting': + list($name, $value) = explode('=', $argument, 2); + db_execute_prepared('REPLACE INTO settings (name, value) VALUES (?, ?)', array($name, $value)); + + break; + case 'drop_registrations': + // What a failed hook registration on an earlier request leaves. + db_execute("DELETE FROM plugin_hooks WHERE name = 'cloud'"); + db_execute("DELETE FROM plugin_realms WHERE plugin = 'cloud'"); + + break; + case 'drop_table': + db_execute('DROP TABLE IF EXISTS `' . preg_replace('/[^a-z_]/', '', $argument) . '`'); + + 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')"); + + break; + case 'credential_flow': + // Create, edit, store a vault credential, read it back, and delete + // an account through the repositories, then search every plugin + // table and the Cacti log for the secret (REQ-CRED-004). + include_once($config['base_path'] . '/plugins/cloud/setup.php'); + cloud_boot(); + + $secret = 'dop_v1_' . bin2hex(random_bytes(32)); + $keyFile = sys_get_temp_dir() . '/cloud-test-' . getmypid() . '.key'; + file_put_contents($keyFile, bin2hex(random_bytes(32))); + chmod($keyFile, 0600); + + $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->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->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 * FROM `' . $table['t'] . '`') as $row) { + if (strpos(implode("\0", array_map('strval', $row)), $secret) !== false) { + $leaks[] = $table['t']; + } + } + } + + if (strpos((string) @file_get_contents(cacti_log_file()), $secret) !== false) { + $leaks[] = 'cacti.log'; + } + + $accounts->delete($id, 1); + unlink($keyFile); + + $result = array('read_back' => $readBack, 'audit' => $audit, 'leaks' => $leaks, 'account_gone' => $accounts->find($id) === null); + + break; + case 'collector_flow': + include($config['base_path'] . '/plugins/cloud/tests/bin/collector-flow.php'); + + break; + case 'uninstall_unbooted': + // What core does on uninstall when cloud_boot() refuses: the PHP 8.0 + // fallback, then core drops whatever is still tracked. + include_once($config['base_path'] . '/plugins/cloud/include/unbooted-uninstall.php'); + cloud_uninstall_unbooted(); + api_plugin_db_changes_remove('cloud'); + api_plugin_remove_hooks('cloud'); + api_plugin_remove_realms('cloud'); + db_execute("DELETE FROM plugin_config WHERE directory = 'cloud'"); + + break; + 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')"); + $viewer = (int) db_fetch_insert_id(); + db_execute("DELETE FROM plugin_realms WHERE plugin = 'cloud'"); + db_execute("DELETE FROM plugin_hooks WHERE name = 'cloud'"); + $_SESSION['sess_user_id'] = $viewer; + 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))); + db_execute("REPLACE INTO settings (name, value) VALUES ('admin_user', '1')"); + + break; + case 'collector_second': + case 'collector_victim': + case 'collector_kill': + include($config['base_path'] . '/plugins/cloud/tests/bin/collector-restart.php'); + + break; + case 'state': + break; + default: + fwrite(STDERR, "Unknown action $action\n"); + exit(2); +} + +$output = ob_get_clean(); + +$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) { + $tables[$row['t']] = (int) db_fetch_cell('SELECT COUNT(*) FROM `' . $row['t'] . '`'); +} + +print json_encode(array( + 'result' => $result, + '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'), + 'tables' => $tables, +), JSON_PRETTY_PRINT) . PHP_EOL; diff --git a/tests/bin/page-check.php b/tests/bin/page-check.php new file mode 100644 index 0000000..e0358d2 --- /dev/null +++ b/tests/bin/page-check.php @@ -0,0 +1,89 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Log in as the Cacti admin user over HTTP and request a list of pages, + * failing on any non-200 response, PHP error text, or missing Cacti footer. + * Used to show that core pages keep loading with the plugin installed on an + * unsupported PHP. Disposable databases only: it resets the admin password. + * Must parse on PHP 8.0. + * + * php plugins/cloud/tests/bin/page-check.php http://127.0.0.1:8080/cacti/ index.php host.php ... + */ + +chdir(dirname(__DIR__, 4)); + +require('./include/cli_check.php'); + +if (getenv('CLOUD_TEST_DATABASE') !== 'disposable') { + fwrite(STDERR, "Refusing to reset the admin password: set CLOUD_TEST_DATABASE=disposable\n"); + exit(2); +} + +$base = rtrim($argv[1], '/') . '/'; +$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))); + +$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)); + + if ($post !== null) { + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post)); + } + + $body = (string) curl_exec($ch); + + return array((int) curl_getinfo($ch, CURLINFO_HTTP_CODE), $body); +} + +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)); + +$failures = 0; + +foreach ($pages as $page) { + list($code, $body) = page_get($base . $page, $jar); + + $error = preg_match('/(Fatal error|Parse error|Warning:|Uncaught)/', $body, $m) ? $m[1] : ''; + $ok = $code === 200 && $error === '' && strpos($body, 'logout.php') !== false; + + // A plugin page on a refused runtime must say why instead of failing. + if (strpos($page, 'plugins/cloud/') === 0) { + $refused = preg_match('/The Cloud plugin (requires PHP [0-9.]+ or later|is not enabled)/', $body, $r) === 1; + $ok = $ok && (getenv('CLOUD_EXPECT_REFUSAL') !== '1' || $refused); + + print ' page shows: ' . ($refused ? $r[0] : 'no refusal') . PHP_EOL; + } + + printf("%s %-40s HTTP %d %s\n", $ok ? 'PASS' : 'FAIL', $page, $code, $error); + + $failures += $ok ? 0 : 1; +} + +unlink($jar); + +exit($failures > 0 ? 1 : 0); diff --git a/tests/bin/page-permissions.php b/tests/bin/page-permissions.php new file mode 100644 index 0000000..2de6b6d --- /dev/null +++ b/tests/bin/page-permissions.php @@ -0,0 +1,218 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Page permissions and POST-only actions over HTTP (#28). Logs in to a + * running Cacti as three users and checks each plugin page: + * + * admin Cloud View and Cloud Admin: both pages load + * viewer Console and Cloud View: health loads, accounts is denied + * norealm Console only: both pages are denied + * + * Then shows that a delete sent as GET, or as POST without the csrf-magic + * token, has no effect, and that the same delete as a proper POST works. + * Last, it saves an account with a vault credential through the form and + * searches every response, the Cacti log, and every plugin table for the + * credential (#32). + * Disposable databases only: it resets the admin password and adds users. + * Must parse on PHP 8.0. + * + * CLOUD_TEST_DATABASE=disposable php plugins/cloud/tests/bin/page-permissions.php http://127.0.0.1:8080/cacti/ + */ + +chdir(dirname(__DIR__, 4)); + +require('./include/cli_check.php'); + +if (getenv('CLOUD_TEST_DATABASE') !== 'disposable') { + fwrite(STDERR, "Set CLOUD_TEST_DATABASE=disposable\n"); + exit(2); +} + +$base = rtrim($argv[1], '/') . '/plugins/cloud/'; +$root = rtrim($argv[1], '/') . '/'; +$password = 'Cloud-' . bin2hex(random_bytes(8)); +$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'"); + +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)); + $id = (int) db_fetch_insert_id(); + + foreach ($realms as $realm) { + db_execute_prepared('INSERT INTO user_auth_realm (realm_id, user_id) VALUES (?, ?)', array($realm, $id)); + } +} + +function perm_expect($ok, $message) { + global $failures; + + print ($ok ? 'PASS ' : 'FAIL ') . $message . PHP_EOL; + $failures += $ok ? 0 : 1; +} + +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)); + + if ($post !== null) { + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post)); + } + + $body = (string) curl_exec($ch); + + return array((int) curl_getinfo($ch, CURLINFO_HTTP_CODE), $body); +} + +function perm_token($body) { + return preg_match('/csrfMagicToken\s*=\s*"([^"]+)"/', $body, $m) ? $m[1] : ''; +} + +function perm_login($user) { + global $root, $password; + + $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)); + + 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')); +$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) { + $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)"); + + // 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'); + } + } + + unlink($jar); +} + +$jar = perm_login('admin'); +$exists = function () use ($probe) { + return (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_cloud_account WHERE id = ?', array($probe)) === 1; +}; + +// 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_http($base . 'cloud_accounts.php?action=delete&id=' . $probe, $jar); +perm_expect($exists(), 'a delete sent as GET has no effect'); + +perm_http($base . 'cloud_accounts.php', $jar, array('action' => 'delete', 'id' => $probe)); +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_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 +// log line, and no plugin table. +$keyFile = sys_get_temp_dir() . '/cloud-perm-' . bin2hex(random_bytes(4)) . '.key'; +file_put_contents($keyFile, bin2hex(random_bytes(32))); +chmod($keyFile, 0600); +db_execute_prepared("REPLACE INTO settings (name, value) VALUES ('cloud_vault_key_file', ?)", array($keyFile)); + +$secret = 'dop_v1_' . bin2hex(random_bytes(32)); +$probeName = 'Secret probe ' . bin2hex(random_bytes(3)); + +// Each response counts as evidence only if the request did what it should: +// [label, HTTP code, body, text the page must show]. +$responses = array(); + +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', +)); +$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) { + 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)); +$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"); +} + +$leaks = array(); + +foreach ($responses as $response) { + if (strpos($response[2], $secret) !== false) { + $leaks[] = $response[0] . ' response'; + } +} + +$log = (string) @file_get_contents($config['base_path'] . '/log/cacti.log'); + +if (strpos($log, $secret) !== false) { + $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 * FROM `' . $table['t'] . '`') as $row) { + if (strpos(implode("\0", array_map('strval', $row)), $secret) !== false) { + $leaks[] = $table['t']; + } + } +} + +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); +unlink($jar); + +exit($failures > 0 ? 1 : 0); diff --git a/tests/bin/php-guard-check.php b/tests/bin/php-guard-check.php new file mode 100644 index 0000000..f738bcb --- /dev/null +++ b/tests/bin/php-guard-check.php @@ -0,0 +1,125 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Proves the PHP 8.2 guard against a real Cacti install, on whatever PHP runs + * this script. Run from the Cacti root as the poller user: + * + * php plugins/cloud/tests/bin/php-guard-check.php + * + * Below 8.2 it expects install and enable to be refused with a message, no + * tables, hooks, or realms, no plugin class loaded, and every hook shim to + * return quietly even when hooks were registered by an earlier, supported + * PHP. On 8.2 and later it expects install and enable to succeed. + * + * This file must itself parse on PHP 8.0. Exits non-zero on any failure. + */ + +chdir(dirname(__DIR__, 4)); + +require('./include/cli_check.php'); +require_once($config['base_path'] . '/lib/plugins.php'); +require_once($config['base_path'] . '/lib/poller.php'); + +$failures = 0; + +function guard_expect($condition, $message) { + global $failures; + + print ($condition ? 'PASS ' : 'FAIL ') . $message . PHP_EOL; + + if (!$condition) { + $failures++; + } +} + +function guard_state() { + return array( + '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\\_%'"), + ); +} + +/* + * Every hook callback setup.php defines, called as Cacti would. Listed by + * name so that this file needs no plugin class to enumerate them. + */ +function guard_call_shims() { + $nav = array('index.php:' => array('title' => 'Console')); + + foreach (array('cloud_config_arrays', 'cloud_config_settings', 'cloud_poller_bottom') as $function) { + if (function_exists($function)) { + $function(); + } + } + + if (function_exists('cloud_draw_navigation_text')) { + guard_expect(cloud_draw_navigation_text($nav) === $nav, 'draw_navigation_text returns the navigation unchanged'); + } + + // Core's own dispatch, as every page load does. + api_plugin_hook('config_arrays'); + api_plugin_hook('config_settings'); + 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'); +} + +$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; + +if (!$supported && ($preexisting['status'] == 1 || $preexisting['hooks'] > 0)) { + // Enabled under a supported PHP, then PHP was downgraded. Cacti + // still calls the shims; each must return before loading any class. + include_once($config['base_path'] . '/plugins/cloud/setup.php'); + + guard_call_shims(); + guard_expect(plugin_cloud_check_config() === false, 'check_config refuses'); + guard_expect(!class_exists('Somethingwithproof\\Cloud\\Log', false), 'no plugin class was loaded'); + guard_expect(guard_state()['tables'] === $preexisting['tables'], 'plugin tables were not touched'); +} else { + ob_start(); + api_plugin_install('cloud'); + api_plugin_enable('cloud'); + ob_end_clean(); + + $state = guard_state(); + + if ($supported) { + guard_expect($state['status'] == 1, 'install and enable succeed (status ' . $state['status'] . ')'); + 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(!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())); + guard_expect($logged > 0, 'the refusal naming PHP 8.2.0 was logged'); + + guard_call_shims(); + } +} + +exit($failures > 0 ? 1 : 0); diff --git a/tests/bootstrap-integration.php b/tests/bootstrap-integration.php new file mode 100644 index 0000000..9449373 --- /dev/null +++ b/tests/bootstrap-integration.php @@ -0,0 +1,67 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Integration bootstrap. The tests drive Cacti in separate PHP processes, as + * plugins.php and the CLI tools do, so nothing from Cacti is loaded here. + */ + +$cacti = rtrim((string) getenv('CACTI_PATH'), '/'); + +if ($cacti === '' || !is_file($cacti . '/include/config.php') || !is_dir($cacti . '/plugins/cloud')) { + fwrite(STDERR, "Set CACTI_PATH to an installed Cacti with this plugin at plugins/cloud.\n"); + exit(2); +} + +if (getenv('CLOUD_TEST_DATABASE') !== 'disposable') { + fwrite(STDERR, "Set CLOUD_TEST_DATABASE=disposable: these tests install and uninstall the plugin.\n"); + exit(2); +} + +/** + * Run tests/bin/lifecycle.php in a fresh PHP process and decode its state. + * + * @return array + */ +function lifecycle(string $action, string $argument = ''): array { + $cacti = rtrim((string) getenv('CACTI_PATH'), '/'); + $command = [PHP_BINARY, $cacti . '/plugins/cloud/tests/bin/lifecycle.php', $action]; + + if ($argument !== '') { + $command[] = $argument; + } + + $process = proc_open($command, [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, $cacti); + $stdout = stream_get_contents($pipes[1]); + $stderr = stream_get_contents($pipes[2]); + + fclose($pipes[1]); + fclose($pipes[2]); + + $status = proc_close($process); + $state = json_decode((string) $stdout, true); + + if ($status !== 0 || !is_array($state)) { + throw new RuntimeException("lifecycle.php $action failed ($status): $stderr $stdout"); + } + + $state['stderr'] = $stderr; + + return $state; +} diff --git a/tests/bootstrap-unit.php b/tests/bootstrap-unit.php new file mode 100644 index 0000000..4a4ae3f --- /dev/null +++ b/tests/bootstrap-unit.php @@ -0,0 +1,162 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +/* + * Unit test bootstrap. Stubs the few Cacti helpers the plugin calls, so the + * suite needs no database or Cacti checkout. Each stub records its calls in + * $GLOBALS for tests to read. + */ + +if (!defined('POLLER_VERBOSITY_MEDIUM')) { + define('POLLER_VERBOSITY_NONE', 1); + define('POLLER_VERBOSITY_LOW', 2); + define('POLLER_VERBOSITY_MEDIUM', 3); + define('POLLER_VERBOSITY_HIGH', 4); + define('POLLER_VERBOSITY_DEBUG', 5); +} + +if (!defined('MESSAGE_LEVEL_ERROR')) { + define('MESSAGE_LEVEL_ERROR', 3); +} + +$GLOBALS['__cloud_log'] = []; + +if (!function_exists('__')) { + // Core's __() (include/global_languages.php) passes every argument to + // sprintf(), the trailing text domain included, when the text has a + // placeholder. A placeholder therefore takes the domain unless the caller + // supplied values before it: __('%d s', $n, 'cloud'), never + // sprintf(__('%d s', 'cloud'), $n). + function __() { + $args = func_get_args(); + + if (count($args) === 1 || preg_match('/%(%|c|[-0-9.]*[bdeEfFgGhHosuxX])/', $args[0]) !== 1) { + return $args[0]; + } + + return call_user_func_array('sprintf', $args); + } +} + +if (!function_exists('cacti_log')) { + function cacti_log($string, $output = false, $environ = 'CMDPHP', $level = '') { + $GLOBALS['__cloud_log'][] = ['message' => $string, 'environ' => $environ, 'level' => $level]; + + return true; + } +} + +$GLOBALS['__cloud_options'] = []; + +if (!function_exists('read_config_option')) { + function read_config_option($config_name, $force = false) { + return $GLOBALS['__cloud_options'][$config_name] ?? ''; + } +} + +// Repositories in unit tests talk to these stubs. A test reads the +// statements from $GLOBALS['__cloud_db_exec'] and queues query results in +// $GLOBALS['__cloud_db_rows'] (keyed by a substring of the SQL). +$GLOBALS['__cloud_db_exec'] = []; +$GLOBALS['__cloud_db_rows'] = []; + +function cloud_test_rows(string $sql): mixed { + foreach ($GLOBALS['__cloud_db_rows'] as $needle => $rows) { + if (str_contains($sql, $needle)) { + return $rows; + } + } + + return []; +} + +if (!function_exists('db_execute_prepared')) { + function db_execute_prepared($sql, $params = [], $log = true, $db_conn = false, $log_function = null) { + $GLOBALS['__cloud_db_exec'][] = ['sql' => $sql, 'params' => $params]; + + return true; + } +} + +if (!function_exists('db_fetch_assoc_prepared')) { + function db_fetch_assoc_prepared($sql, $params = [], $log = true, $db_conn = false, $log_function = null) { + return cloud_test_rows($sql); + } +} + +if (!function_exists('db_fetch_row_prepared')) { + function db_fetch_row_prepared($sql, $params = [], $log = true, $db_conn = false, $log_function = null) { + $rows = cloud_test_rows($sql); + + return is_array($rows) && isset($rows[0]) ? $rows[0] : []; + } +} + +// Transactions are recorded as BEGIN, COMMIT, and ROLLBACK statements. +// @@in_transaction answers from $GLOBALS['__cloud_in_tx'] in order, then 1, +// so a test can play InnoDB ending a transaction on a deadlock. +$GLOBALS['__cloud_in_tx'] = []; + +if (!function_exists('db_begin_transaction')) { + function db_begin_transaction($db_conn = false) { + $GLOBALS['__cloud_db_exec'][] = ['sql' => 'BEGIN', 'params' => []]; + + return true; + } + + function db_commit_transaction($db_conn = false) { + $GLOBALS['__cloud_db_exec'][] = ['sql' => 'COMMIT', 'params' => []]; + + return true; + } + + function db_rollback_transaction($db_conn = false) { + $GLOBALS['__cloud_db_exec'][] = ['sql' => 'ROLLBACK', 'params' => []]; + + return true; + } +} + +if (!function_exists('db_fetch_cell_prepared')) { + 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']); + } + + $rows = cloud_test_rows($sql); + + return is_array($rows) && isset($rows[0]) ? reset($rows[0]) : 0; + } +} + +if (!function_exists('db_fetch_insert_id')) { + function db_fetch_insert_id($db_conn = false) { + return 1; + } +} + +$GLOBALS['config'] = [ + 'base_path' => '/var/www/cacti', + 'library_path' => '/var/www/cacti/lib', + 'poller_id' => 1, + 'is_web' => false, +]; + +require_once dirname(__DIR__) . '/setup.php'; +require_once dirname(__DIR__) . '/include/autoload.php'; diff --git a/tests/lint-workflows.sh b/tests/lint-workflows.sh new file mode 100755 index 0000000..5dd9066 --- /dev/null +++ b/tests/lint-workflows.sh @@ -0,0 +1,48 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2026 Thomas Vincent +# SPDX-License-Identifier: GPL-2.0-or-later +# +# This file is part of plugin_cloud, a plugin for Cacti. +# https://github.com/somethingwithproof/plugin_cloud +# +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the Free +# Software Foundation; either version 2 of the License, or (at your option) +# any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +# more details. + +# Lint the GitHub Actions workflows with actionlint (syntax, expressions, +# ShellCheck on run: steps) and zizmor (security: script injection, excessive +# permissions, unpinned actions, credential persistence). CI and a developer +# machine run this same file, so the pinned tool versions live only here. +# +# sh tests/lint-workflows.sh +# +# Needs Docker. zizmor's online audits (impostor commits, known-vulnerable +# actions) run when GH_TOKEN is set in the environment and are skipped, with a +# note, when it is not. Exits non-zero on any finding. +set -eu + +ACTIONLINT=rhysd/actionlint:1.7.12@sha256:b1934ee5f1c509618f2508e6eb47ee0d3520686341fec936f3b79331f9315667 +ZIZMOR=ghcr.io/zizmorcore/zizmor:1.32.0@sha256:3014cc8f68f663935f69b3c3e0e41f5ce102b268d97db13db0f62208747f860d + +PLUGIN=$(cd "$(dirname "$0")/.." && pwd) +status=0 + +echo "== actionlint" +docker run --rm -v "$PLUGIN":/repo:ro -w /repo "$ACTIONLINT" -color || status=1 + +echo "== zizmor" +if [ -n "${GH_TOKEN:-}" ]; then + # The token goes in by name, so its value is never on a command line. + docker run --rm -e GH_TOKEN -v "$PLUGIN":/repo:ro -w /repo "$ZIZMOR" --no-progress --color=always .github || status=1 +else + echo "GH_TOKEN is not set: running zizmor's offline audits only" + docker run --rm -v "$PLUGIN":/repo:ro -w /repo "$ZIZMOR" --offline --no-progress --color=always .github || status=1 +fi + +exit $status diff --git a/tests/phpstan-bootstrap.php b/tests/phpstan-bootstrap.php new file mode 100644 index 0000000..cfee38b --- /dev/null +++ b/tests/phpstan-bootstrap.php @@ -0,0 +1,28 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_cloud, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_cloud + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +// Constants core defines at runtime, so PHPStan can resolve them without a database. +$cacti_root = rtrim((string) getenv('CACTI_PATH'), '/'); + +if ($cacti_root === '' || !is_file($cacti_root . '/include/global_constants.php')) { + fwrite(STDERR, "Set CACTI_PATH to the Cacti root.\n"); + exit(2); +} + +require_once $cacti_root . '/include/global_constants.php'; diff --git a/tests/transport-spike/server.php b/tests/transport-spike/server.php index 5d1107d..9f43995 100644 --- a/tests/transport-spike/server.php +++ b/tests/transport-spike/server.php @@ -128,6 +128,14 @@ function drip($conn, string $bytes, float $interval, float $seconds): void { $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); break; + case '/head': + // Headers only, with a length the body never sends: correct for + // a HEAD response. + send($conn, $ok . "Content-Length: 100\r\n\r\n"); + break; + case '/no-content': + send($conn, "HTTP/1.1 204 No Content\r\nConnection: close\r\nContent-Length: 50\r\n\r\n"); + break; case '/log': $b = json_encode($log); send($conn, $ok . 'Content-Length: ' . strlen($b) . "\r\n\r\n" . $b);