From c79cbfb8828fe2e09956158f5772bedf8458f697 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 04:42:11 -0800 Subject: [PATCH 1/4] test: cover cloud graph permissions and access revoked mid-session The page check now creates a cloud graph on a scope device and views it through Cacti's graph.php as three users: every policy allowed, every policy denied, and denied except for an explicit grant on the scope device. Cloud graphs follow Cacti's graph and device permissions with no plugin layer. It also revokes Cloud View and Cloud Admin from logged-in users the way Cacti's user page does, changing reset_perms, and shows that the open session loses the page and that a form taken before the revocation changes nothing. ss_cloud.php serves nothing over HTTP. Closes #45 Signed-off-by: Thomas Vincent --- tests/bin/page-permissions.php | 136 +++++++++++++++++++++++++++++++-- 1 file changed, 129 insertions(+), 7 deletions(-) diff --git a/tests/bin/page-permissions.php b/tests/bin/page-permissions.php index c8d2f7b..ad56312 100644 --- a/tests/bin/page-permissions.php +++ b/tests/bin/page-permissions.php @@ -27,9 +27,11 @@ * * 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 + * Then 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). + * credential (#32). Last (#45), it views a cloud graph as users allowed and + * denied by Cacti's graph and device permissions, checks that ss_cloud.php + * serves nothing over HTTP, and revokes each realm from a logged-in user. * Disposable databases only: it resets the admin password and adds users. * Must parse on PHP 8.0. * @@ -61,22 +63,34 @@ array(password_hash($password, PASSWORD_DEFAULT)) ); -// Realm 8 is Console access. -foreach (array('viewer' => array(8, $view), 'norealm' => array(8)) as $name => $realms) { +/** + * A user with these realms, every graph policy allow (1) or deny (2). + * + * @return int the user id + */ +function perm_user($name, $realms, $policy = 1) { + global $password; + 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) + "policy_graphs, policy_trees, policy_hosts, policy_graph_templates, enabled) VALUES (?, ?, 0, ?, '', '', ?, ?, ?, " . + "?, 'on')", + array($name, password_hash($password, PASSWORD_DEFAULT), $name, $policy, $policy, $policy, $policy) ); $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)); } + + return $id; } +// Realm 8 is Console access, realm 7 View Graphs. +perm_user('viewer', array(8, $view)); +perm_user('norealm', array(8)); + function perm_expect($ok, $message) { global $failures; @@ -293,6 +307,114 @@ function perm_login($user) { )) ); +// Cloud graphs follow Cacti's graph and device permissions, with no plugin +// layer (REQ-PERM-002): a graph on a scope device, viewed through Cacti. +include_once($config['base_path'] . '/plugins/cloud/setup.php'); +include_once($config['base_path'] . '/lib/api_data_source.php'); +include_once($config['base_path'] . '/lib/api_graph.php'); +include_once($config['base_path'] . '/lib/data_query.php'); +include_once($config['base_path'] . '/lib/template.php'); +include_once($config['base_path'] . '/lib/utility.php'); +cloud_boot(); + +// Permissive: a graph is visible when its graph, device, or template is. +db_execute("REPLACE INTO settings (name, value) VALUES ('graph_auth_method', '1')"); +db_execute_prepared( + "INSERT INTO plugin_cloud_account (provider, name, credential_source) VALUES ('digitalocean', ?, 'vault')", + array('Graph probe') +); +$graphAccount = (int) db_fetch_insert_id(); +$resourceName = 'graph-probe-' . bin2hex(random_bytes(3)); +db_execute_prepared( + "INSERT INTO plugin_cloud_resource (account_id, type, provider_id, name, lifecycle, first_seen, last_seen) + VALUES (?, 'droplet', '7001', ?, 'active', UNIX_TIMESTAMP(), UNIX_TIMESTAMP())", + array($graphAccount, $resourceName) +); +$host = cloud_scope_devices()->create(cloud_accounts()->find($graphAccount)); +$templates = new \Somethingwithproof\Cloud\TemplateRepository(false); +$query = (int) $templates->id('snmp_query', 'data_query/droplet'); +$suggested = array(); +$created = create_complete_graph_from_template( + $templates->id('graph_templates', 'graph_template/do_cpu'), + $host, + array( + 'snmp_query_id' => $query, + 'snmp_index_on' => get_best_data_query_index_type($host, $query), + 'snmp_query_graph_id' => $templates->id('snmp_query_graph', 'data_query_graph/do_cpu'), + 'snmp_index' => '7001', + ), + $suggested +); +$graph = (int) $created['local_graph_id']; +perm_expect($host > 0 && $graph > 0, "a cloud graph exists on scope device $host (graph $graph)"); + +perm_user('graphs', array(7)); +perm_user('nographs', array(7), 2); +db_execute_prepared( + 'INSERT INTO user_auth_perms (user_id, item_id, type) VALUES (?, ?, 3)', + array(perm_user('deviceonly', array(7), 2), $host) +); + +foreach (array('graphs' => true, 'nographs' => false, 'deviceonly' => true) as $user => $allowed) { + $graphJar = perm_login($user); + list($code, $body) = perm_http($root . 'graph.php?action=view&rra_id=all&local_graph_id=' . $graph, $graphJar); + $shown = strpos($body, 'local_graph_id=' . $graph) !== false && strpos($body, 'permission_denied') === false + && stripos($body, 'Permission Denied') === false; + + perm_expect($shown === $allowed, "$user " . ($allowed ? 'sees' : 'is denied') . " the cloud graph (HTTP $code)"); + unlink($graphJar); +} + +// The script server entry point serves nothing over the web, even to an administrator. +list($code, $body) = perm_http($base . 'ss_cloud.php?argv[]=' . $host . '&argv[]=droplet&argv[]=index', $jar); +// Cacti's cli_check.php answers 404, so the file must exist for the 404 to count. +perm_expect( + is_file($config['base_path'] . '/plugins/cloud/ss_cloud.php') + && strpos($body, '7001') === false && strpos($body, $resourceName) === false, + "ss_cloud.php serves no data over HTTP (HTTP $code)" +); + +// Access revoked while logged in (REQ-PERM-001): Cacti's user page removes +// the realm and changes reset_perms, so the open session loses the page. +foreach (array('cloud_health.php' => array('revoked', $view), 'cloud_accounts.php' => array('revokedadmin', $admin)) as + $page => $revoke) { + list($user, $realm) = $revoke; + $id = perm_user($user, array(8, $realm)); + $revokedJar = perm_login($user); + list(, $before) = perm_http($base . $page, $revokedJar); + + db_execute_prepared('DELETE FROM user_auth_realm WHERE user_id = ? AND realm_id = ?', array($id, $realm)); + db_execute_prepared('UPDATE user_auth SET reset_perms = ? WHERE id = ?', array(mt_rand(1, 2147483647), $id)); + + $after = array(); + + foreach (array(1, 2) as $attempt) { + list(, $after[]) = perm_http($base . $page, $revokedJar); + } + + perm_expect( + preg_match('/' . $pages[$page] . '/', $before) === 1 + && preg_match('/' . $pages[$page] . '/', $after[0]) !== 1 + && preg_match('/' . $pages[$page] . '/', $after[1]) !== 1, + "$user loses $page in the same session once the realm is revoked" + ); + + // A form taken before the revocation changes nothing after it. + if ($page === 'cloud_accounts.php') { + perm_http( + $base . 'cloud_accounts.php', + $revokedJar, + array('__csrf_magic' => perm_token($before), 'action' => 'delete', 'id' => $graphAccount) + ); + perm_expect( + (int) db_fetch_cell_prepared('SELECT COUNT(*) FROM plugin_cloud_account WHERE id = ?', array($graphAccount)) === 1, + 'a revoked administrator\'s delete has no effect' + ); + } + + unlink($revokedJar); +} + db_execute("DELETE FROM settings WHERE name = 'cloud_vault_key_file'"); unlink($keyFile); unlink($jar); From e6bf2369e8e2a047b2349b612956a056b611adf9 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 04:49:25 -0800 Subject: [PATCH 2/4] test: draw the revoked user's reset_perms with random_int Signed-off-by: Thomas Vincent --- tests/bin/page-permissions.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/bin/page-permissions.php b/tests/bin/page-permissions.php index ad56312..c8d7279 100644 --- a/tests/bin/page-permissions.php +++ b/tests/bin/page-permissions.php @@ -384,7 +384,7 @@ function perm_login($user) { list(, $before) = perm_http($base . $page, $revokedJar); db_execute_prepared('DELETE FROM user_auth_realm WHERE user_id = ? AND realm_id = ?', array($id, $realm)); - db_execute_prepared('UPDATE user_auth SET reset_perms = ? WHERE id = ?', array(mt_rand(1, 2147483647), $id)); + db_execute_prepared('UPDATE user_auth SET reset_perms = ? WHERE id = ?', array(random_int(1, 2147483647), $id)); $after = array(); From 7ca0550d81d78f35dc484c745f0ab40932547965 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 05:51:18 -0800 Subject: [PATCH 3/4] fix: read credential files only from a directory full administrators set Cloud Admin, which sits below full Cacti administration, chooses each account's credential file. A new Credential File Directory setting on Cacti's Settings page, which only full administrators can change, now bounds that choice: a file must resolve inside it, and the vault key file is never accepted. The setting is empty by default, which refuses credential files. A path outside the directory is refused before the file is opened, with the same reason whatever the file's state. Signed-off-by: Thomas Vincent --- docs/PLAN.md | 2 + lib/CredentialFile.php | 44 +++++++++++++++++- lib/CredentialStore.php | 17 ++++++- lib/HealthWarnings.php | 9 ++-- lib/Settings.php | 14 ++++++ locales/po/cacti.pot | 8 ++++ setup.php | 3 +- tests/Unit/DriverContractTest.php | 6 +-- tests/Unit/HealthWarningsTest.php | 5 +- tests/Unit/VaultTest.php | 76 +++++++++++++++++++++++++++---- tests/bin/collector-flow.php | 2 +- tests/bin/collector-restart.php | 2 +- tests/bin/lifecycle.php | 3 +- 13 files changed, 167 insertions(+), 24 deletions(-) diff --git a/docs/PLAN.md b/docs/PLAN.md index 24d7702..cac64c0 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -270,6 +270,8 @@ Credential sources are vault, credential file, and instance identity ([ADR 0007] | Google Cloud | Service account JSON key; only `client_email`, `private_key`, and `private_key_id` are used | Metadata server (phase 3) | | Azure | Tenant ID, client ID, client secret | Managed identity (phase 4) | +A credential file must sit inside the Credential File Directory, a Cloud setting on Cacti's Settings page. Only full administrators can change it, and it is empty by default, which refuses credential files. Cloud Admin picks an account's file, so without this limit it could name any file the Cacti user can read, the vault key included, and have the collector send it to the provider. A path outside the directory is refused before the file is opened, so the refusal reveals nothing about the file. + Short-lived tokens are cached per collector run. When a provider limits how often tokens can be issued, they are cached in the vault with their expiry. ## Security diff --git a/lib/CredentialFile.php b/lib/CredentialFile.php index b0f98bf..e7e2105 100644 --- a/lib/CredentialFile.php +++ b/lib/CredentialFile.php @@ -29,10 +29,40 @@ public static function pathAcceptable(string $path): bool { return SecureFile::pathAcceptable($path); } + /** + * Whether $path names a file inside $directory, the credential directory a + * full administrator set on Cacti's Settings page. Cloud Admin chooses an + * account's file, so without this it could name any file the Cacti user + * can read and have it sent to the provider. An empty or root directory + * allows nothing. Only directories are resolved; the file itself is not + * touched, and SecureFile refuses a link at the last component. + */ + public static function within(string $path, string $directory): bool { + if (!SecureFile::pathAcceptable($path) || !SecureFile::pathAcceptable($directory)) { + return false; + } + + $root = realpath($directory); + $parent = realpath(dirname($path)); + + return $root !== false && $root !== '/' && $parent !== false + && str_starts_with($parent . '/', rtrim($root, '/') . '/'); + } + /** * @throws CredentialError */ - public static function read(string $path): Secret { + public static function check(string $path, string $directory): void { + self::guard($path, $directory); + SecureFile::check($path, self::MAX_BYTES); + } + + /** + * @throws CredentialError + */ + public static function read(string $path, string $directory): Secret { + self::guard($path, $directory); + $content = trim(SecureFile::read($path, self::MAX_BYTES)); if ($content === '') { @@ -41,4 +71,16 @@ public static function read(string $path): Secret { return new Secret($content); } + + /** + * Refuse a path outside the directory before opening it, so the reason + * says nothing about files there. + * + * @throws CredentialError + */ + private static function guard(string $path, string $directory): void { + if (!self::within($path, $directory)) { + throw CredentialError::because('the file is not in the credential directory set in the Cloud settings'); + } + } } diff --git a/lib/CredentialStore.php b/lib/CredentialStore.php index f10dca4..97ee623 100644 --- a/lib/CredentialStore.php +++ b/lib/CredentialStore.php @@ -30,6 +30,7 @@ final class CredentialStore { public function __construct( private readonly SecretRepository $secrets, private readonly string $keyFile, + private readonly string $credentialDir, ) { } @@ -38,7 +39,7 @@ public function __construct( */ public function credentialFor(Account $account): Secret { return match ($account->credentialSource) { - CredentialSource::File => CredentialFile::read($account->credentialFile), + CredentialSource::File => $this->fromFile($account->credentialFile), CredentialSource::Vault => $this->fromVault($account->id), CredentialSource::Instance => throw CredentialError::because('instance identity is not available for this provider'), }; @@ -72,6 +73,20 @@ public function forget(int $accountId): void { /** * @throws CredentialError */ + /** + * @throws CredentialError + */ + private function fromFile(string $path): Secret { + // The vault key may share the directory; it is never a credential. + $file = realpath($path); + + if ($file !== false && $file === realpath($this->keyFile)) { + throw CredentialError::because('the file is the vault key file'); + } + + return CredentialFile::read($path, $this->credentialDir); + } + private function fromVault(int $accountId): Secret { $entry = $this->secrets->load($accountId, SecretRepository::CREDENTIAL); diff --git a/lib/HealthWarnings.php b/lib/HealthWarnings.php index 1da27ff..eb053c8 100644 --- a/lib/HealthWarnings.php +++ b/lib/HealthWarnings.php @@ -31,7 +31,8 @@ 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 + * @param \Closure(string, string): void $fileCheck throws CredentialError for an unusable credential + * file, given its path and the credential directory */ public function __construct( private readonly \Closure $keyCheck, @@ -44,8 +45,8 @@ public static function production(): self { static function (string $path): void { VaultKey::fromFile($path); }, - static function (string $path): void { - SecureFile::check($path, CredentialFile::MAX_BYTES); + static function (string $path, string $directory): void { + CredentialFile::check($path, $directory); }, ); } @@ -78,7 +79,7 @@ public function for(Settings $settings, array $accounts, int $pollerInterval): a if ($account->credentialSource === CredentialSource::File) { try { - ($this->fileCheck)($account->credentialFile); + ($this->fileCheck)($account->credentialFile, $settings->credentialDir); } catch (CredentialError $e) { $warnings[] = [ 'message' => __('%s: the credential file cannot be used: %s.', $account->name, $e->getMessage(), 'cloud'), diff --git a/lib/Settings.php b/lib/Settings.php index 9e8588d..a6d2e32 100644 --- a/lib/Settings.php +++ b/lib/Settings.php @@ -28,6 +28,7 @@ final readonly class Settings { public const NAMES = [ 'cloud_vault_key_file', + 'cloud_credential_dir', 'cloud_collector_budget', 'cloud_uninstall_keep_tables', ]; @@ -39,6 +40,7 @@ public function __construct( public string $vaultKeyFile, public int $collectorBudget, public bool $keepTablesOnUninstall, + public string $credentialDir = '', ) { } @@ -59,6 +61,7 @@ public static function fromRow(array $row): self { $row, 'cloud_uninstall_keep_tables' ) : true, + credentialDir: Row::string($row, 'cloud_credential_dir'), ); } @@ -88,6 +91,17 @@ public static function form(): array { 'max_length' => '255', 'size' => '60', ], + 'cloud_credential_dir' => [ + 'friendly_name' => __('Credential File Directory', 'cloud'), + 'description' => __( + 'Absolute path to the directory that holds credential files. An account can read its credential from a file only inside it, never the vault key file. Empty, the default, refuses credential files. Cloud Admin chooses the file, so keep only cloud credentials here.', + 'cloud' + ), + 'method' => 'textbox', + 'default' => '', + 'max_length' => '255', + 'size' => '60', + ], 'cloud_header_collector' => [ 'friendly_name' => __('Collector', 'cloud'), 'method' => 'spacer', diff --git a/locales/po/cacti.pot b/locales/po/cacti.pot index bb13d8c..138301e 100644 --- a/locales/po/cacti.pot +++ b/locales/po/cacti.pot @@ -446,6 +446,14 @@ msgstr "" 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 "Credential File Directory" +msgstr "" + +#: lib/Settings.php +msgid "Absolute path to the directory that holds credential files. An account can read its credential from a file only inside it, never the vault key file. Empty, the default, refuses credential files. Cloud Admin chooses the file, so keep only cloud credentials here." +msgstr "" + #: lib/Settings.php msgid "Collector" msgstr "" diff --git a/setup.php b/setup.php index 00a6d0f..3cb1637 100644 --- a/setup.php +++ b/setup.php @@ -182,7 +182,8 @@ function cloud_require_post(string $page, array $actions): void { function cloud_credentials(): \Somethingwithproof\Cloud\CredentialStore { return new \Somethingwithproof\Cloud\CredentialStore( new \Somethingwithproof\Cloud\SecretRepository(false, new \Somethingwithproof\Cloud\SystemClock()), - cloud_settings()->vaultKeyFile + cloud_settings()->vaultKeyFile, + cloud_settings()->credentialDir ); } diff --git a/tests/Unit/DriverContractTest.php b/tests/Unit/DriverContractTest.php index fbd76ee..e8f3d46 100644 --- a/tests/Unit/DriverContractTest.php +++ b/tests/Unit/DriverContractTest.php @@ -134,7 +134,7 @@ function cloud_verify_with(?int $status, string $source = 'file'): VerifyStatus $clock = new FixedClock(1_800_000_000); $verifier = new Verifier( $drivers, - new CredentialStore(new SecretRepository(false, $clock), $dir . '/missing.key'), + new CredentialStore(new SecretRepository(false, $clock), $dir . '/missing.key', $dir), new AccountRepository(false, $clock) ); $result = $verifier->verify($account, 1); @@ -175,7 +175,7 @@ function cloud_verify_with(?int $status, string $source = 'file'): VerifyStatus $clock = new FixedClock(1); $verifier = new Verifier( new Drivers(cloud_canned(200)), - new CredentialStore(new SecretRepository(false, $clock), '/nonexistent'), + new CredentialStore(new SecretRepository(false, $clock), '/nonexistent', ''), new AccountRepository(false, $clock) ); @@ -193,7 +193,7 @@ function cloud_verify_with(?int $status, string $source = 'file'): VerifyStatus $clock = new FixedClock(1); $verifier = new Verifier( $drivers, - new CredentialStore(new SecretRepository(false, $clock), '/nonexistent'), + new CredentialStore(new SecretRepository(false, $clock), '/nonexistent', ''), new AccountRepository(false, $clock) ); diff --git a/tests/Unit/HealthWarningsTest.php b/tests/Unit/HealthWarningsTest.php index 7809f6f..cc2bc69 100644 --- a/tests/Unit/HealthWarningsTest.php +++ b/tests/Unit/HealthWarningsTest.php @@ -59,7 +59,10 @@ function cloud_warn_account(array $row = []): Account { } function cloud_warnings(string $key, array $accounts, int $poller = 300): array { - return HealthWarnings::production()->for(Settings::fromRow(['cloud_vault_key_file' => $key]), $accounts, $poller); + // Credential files live beside the key in these fixtures. + $settings = Settings::fromRow(['cloud_vault_key_file' => $key, 'cloud_credential_dir' => dirname($key)]); + + return HealthWarnings::production()->for($settings, $accounts, $poller); } it('has no warnings for a usable key, safe files, and matching intervals', function () { diff --git a/tests/Unit/VaultTest.php b/tests/Unit/VaultTest.php index 723e083..ee04205 100644 --- a/tests/Unit/VaultTest.php +++ b/tests/Unit/VaultTest.php @@ -17,10 +17,14 @@ * more details. */ +use Somethingwithproof\Cloud\Account; use Somethingwithproof\Cloud\CredentialError; use Somethingwithproof\Cloud\CredentialFile; +use Somethingwithproof\Cloud\CredentialStore; +use Somethingwithproof\Cloud\FixedClock; use Somethingwithproof\Cloud\Redactor; use Somethingwithproof\Cloud\Secret; +use Somethingwithproof\Cloud\SecretRepository; use Somethingwithproof\Cloud\Vault; use Somethingwithproof\Cloud\VaultEntry; use Somethingwithproof\Cloud\VaultKey; @@ -149,18 +153,70 @@ function cloud_refusal(callable $read): string { 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') + mkdir($dir . '/sub'); + $read = fn (string $path): Secret => CredentialFile::read($path, $dir); + + expect($read(cloud_file($dir, 'ok', CLOUD_TEST_SECRET . "\n"))->reveal())->toBe(CLOUD_TEST_SECRET) + ->and(cloud_refusal(fn () => $read('token')))->toContain('credential directory') + ->and(cloud_refusal(fn () => $read($dir . '/link')))->toContain('symbolic link') + ->and(cloud_refusal(fn () => $read($dir . '/sub')))->toContain('not a regular file') + ->and(cloud_refusal(fn () => $read(cloud_file($dir, 'open', CLOUD_TEST_SECRET, 0644))))->toContain('other users') + ->and(cloud_refusal(fn () => $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)))) + cloud_refusal(fn () => $read(cloud_file($dir, 'big', str_repeat('a', CredentialFile::MAX_BYTES + 1)))) )->toContain('larger than allowed'); + + rmdir($dir . '/sub'); +}); + +it('reads credential files only inside the directory a full administrator set', function () { + $dir = $this->dir; + $token = cloud_file($dir, 'token', CLOUD_TEST_SECRET); + mkdir($dir . '/nested'); + $deep = cloud_file($dir . '/nested', 'token', CLOUD_TEST_SECRET); + mkdir($dir . '/other'); + $other = cloud_file($dir . '/other', 'token', CLOUD_TEST_SECRET); + symlink($dir . '/other', $dir . '/nested/escape'); + + $reason = 'the file is not in the credential directory set in the Cloud settings'; + + expect(CredentialFile::read($token, $dir)->reveal())->toBe(CLOUD_TEST_SECRET) + ->and(CredentialFile::read($deep, $dir)->reveal())->toBe(CLOUD_TEST_SECRET) + ->and(CredentialFile::read($deep, $dir . '/nested/')->reveal())->toBe(CLOUD_TEST_SECRET) + // No directory set, the root, a sibling, or a link out of it: refused. + ->and(cloud_refusal(fn () => CredentialFile::read($token, '')))->toBe($reason) + ->and(cloud_refusal(fn () => CredentialFile::read($token, '/')))->toBe($reason) + ->and(cloud_refusal(fn () => CredentialFile::read($other, $dir . '/nested')))->toBe($reason) + ->and(cloud_refusal(fn () => CredentialFile::read($dir . '/nested/escape/token', $dir . '/nested')))->toBe($reason) + ->and(cloud_refusal(fn () => CredentialFile::read($dir . '/nestedx/token', $dir . '/nested')))->toBe($reason) + // Outside, a missing file and an unsafe one are refused alike. + ->and(cloud_refusal(fn () => CredentialFile::read($dir . '/other/none', $dir . '/nested')))->toBe($reason) + ->and(cloud_refusal(fn () => CredentialFile::check($other, $dir . '/nested')))->toBe($reason); + + foreach (['nested/escape', 'nested/token', 'other/token'] as $file) { + unlink($dir . '/' . $file); + } + + rmdir($dir . '/nested'); + rmdir($dir . '/other'); +}); + +it('never uses the vault key file as a credential', function () { + $key = cloud_file($this->dir, 'vault.key', bin2hex(random_bytes(32))); + $store = new CredentialStore(new SecretRepository(false, new FixedClock(1)), $key, $this->dir); + $row = [ + 'id' => 4, + 'provider' => 'digitalocean', + 'name' => 'Ops', + 'credential_source' => 'file', + 'credential_file' => $key, + 'admin_state' => 'enabled', + ]; + + expect(cloud_refusal(fn () => $store->credentialFor(Account::fromRow($row))))->toBe('the file is the vault key file') + ->and($store->credentialFor( + Account::fromRow(['credential_file' => cloud_file($this->dir, 'tok', CLOUD_TEST_SECRET)] + $row) + )->reveal())->toBe(CLOUD_TEST_SECRET); }); it('never puts secret material in a refusal message', function () { diff --git a/tests/bin/collector-flow.php b/tests/bin/collector-flow.php index d8e45bd..058fdec 100644 --- a/tests/bin/collector-flow.php +++ b/tests/bin/collector-flow.php @@ -148,7 +148,7 @@ function flow_collector($clock, $holder) { return new Collector( new \Somethingwithproof\Cloud\AccountRepository(false, $clock), $drivers, - new CredentialStore(new SecretRepository(false, $clock), '/nonexistent'), + new CredentialStore(new SecretRepository(false, $clock), '/nonexistent', $GLOBALS['flow_dir']), new LeaseRepository(false, $clock), new ResourceRepository(false, $clock), new SeriesRepository(false), new ObservationRepository(false), new HealthRepository(false), new Redactor(), $clock, $holder ); diff --git a/tests/bin/collector-restart.php b/tests/bin/collector-restart.php index 5db4ad0..8333a10 100644 --- a/tests/bin/collector-restart.php +++ b/tests/bin/collector-restart.php @@ -118,7 +118,7 @@ function restart_collector(FixedClock $clock, string $holder): Collector { return new Collector( new \Somethingwithproof\Cloud\AccountRepository(false, $clock), $drivers, - new CredentialStore(new SecretRepository(false, $clock), '/nonexistent'), + new CredentialStore(new SecretRepository(false, $clock), '/nonexistent', dirname($GLOBALS['restart_token'])), new LeaseRepository(false, $clock), new ResourceRepository(false, $clock), new SeriesRepository(false), new ObservationRepository(false), new HealthRepository(false), new Redactor(), $clock, $holder ); diff --git a/tests/bin/lifecycle.php b/tests/bin/lifecycle.php index 6a1ab84..c9e6e3d 100644 --- a/tests/bin/lifecycle.php +++ b/tests/bin/lifecycle.php @@ -381,7 +381,8 @@ $accounts = new \Somethingwithproof\Cloud\AccountRepository(false, $clock); $store = new \Somethingwithproof\Cloud\CredentialStore( new \Somethingwithproof\Cloud\SecretRepository(false, $clock), - $keyFile + $keyFile, + '' ); $input = array( 'provider' => 'digitalocean', From fd5f1fc9cba4bc7a6a59236f20bf8dc929d18d5c Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 15 Nov 2026 23:59:37 -0800 Subject: [PATCH 4/4] test: pass the discovery fixture credential directory Signed-off-by: Thomas Vincent --- tests/bin/discover.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/bin/discover.php b/tests/bin/discover.php index b97d6fa..33dc019 100644 --- a/tests/bin/discover.php +++ b/tests/bin/discover.php @@ -111,7 +111,7 @@ public function estimate(array $requests, int $intervalSeconds): UsageEstimate { $result = (new Collector( new \Somethingwithproof\Cloud\AccountRepository(false, $discover_clock), $discover_drivers, - new CredentialStore(new \Somethingwithproof\Cloud\SecretRepository(false, $discover_clock), '/nonexistent'), + new CredentialStore(new \Somethingwithproof\Cloud\SecretRepository(false, $discover_clock), '/nonexistent', $discover_dir), new \Somethingwithproof\Cloud\LeaseRepository(false, $discover_clock), new \Somethingwithproof\Cloud\ResourceRepository(false, $discover_clock), new \Somethingwithproof\Cloud\SeriesRepository(false),