Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Keep copied API calls on one literal target
pulse-triage[bot]2df2159b07bb
diff --git a/docs/API.md b/docs/API.mdindex f736e8ad8e..727ad0f143 100644--- a/docs/API.md+++ b/docs/API.md@@ -84,7 +84,7 @@ pulse_api() (chmod 600 "$auth_file" || exit "$?"result_file=$(mktemp "$auth_dir/api-response.XXXXXX") || exit "$?"curl_exit=0- status=$(curl --disable --fail-with-body --silent --show-error \+ status=$(curl --disable --fail-with-body --silent --show-error --globoff \--proto '=http' --noproxy 127.0.0.1 --connect-timeout 5 --max-time 20 \--header "@$auth_file" --output "$result_file" --write-out '%{http_code}' \"$@" "http://127.0.0.1:7655$api_path") || curl_exit=$?@@ -127,6 +127,13 @@ each administrative change separately and check its current state afterwards.A timeout or incomplete response can occur **after a change was applied**;do not repeat a POST, PUT or DELETE merely because the response was lost.+Keep `--globoff`: shell quotes alone do not disable curl's URL globbing. Without+it, a path containing a brace list such as `{review,ops}` or a range such as+`[1-3]` can send several requests, including several POST, PUT or DELETE+requests. The helper treats these characters literally, not as a batch of+targets. Still quote the whole path in the shell, and URL-encode dynamic resource+IDs and query values; `--globoff` does not encode them for you.+Keep `--disable` first: it ignores local curl configuration that could enabletrace output, bypass TLS or follow redirects. On an authentication-enabledinstance, the protected summary checks token access; `/api/health` is publicdiff --git a/frontend-modern/browser-tests/api-auth-help.cjs b/frontend-modern/browser-tests/api-auth-help.cjsnew file mode 100644index 0000000000..0ced59bc8c--- /dev/null+++ b/frontend-modern/browser-tests/api-auth-help.cjs@@ -0,0 +1,110 @@+// Consume the shipped API guide through the production Docs page/router.+// Shell transport is proved separately with real curl and synthetic fixtures.+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { createHash } = require('node:crypto');+const { chromium, webkit } = require('playwright');++(async () => {+ const root = path.resolve('frontend-modern');+ const artifacts = path.join(root, 'node_modules', 'api-auth-browser');+ fs.mkdirSync(artifacts, { recursive: true });+ const guide = fs.readFileSync(path.join(root, 'public/docs/API.md'), 'utf8');+ const helper = [...guide.matchAll(/```bash\n([\s\S]*?)```/g)]+ .map(match => match[1].trim()).find(block => block.startsWith('pulse_api() ('));+ assert.ok(helper);+ const port = 5259;+ process.chdir(root);+ const { createServer } = await import(path.join(root, 'node_modules/vite/dist/node/index.js'));+ const server = await createServer({+ root, configFile: path.join(root, 'vite.config.ts'),+ cacheDir: path.join(root, 'node_modules', '.vite-api-auth'),+ server: { host: '127.0.0.1', port, strictPort: true },+ optimizeDeps: { noDiscovery: true, include: [] },+ });+ const results = [];+ let browser;+ try {+ await server.listen();+ for (const [engine, width, tone] of [['chromium', 1280, 'light'], ['webkit', 390, 'dark']]) {+ browser = await { chromium, webkit }[engine].launch(engine === 'chromium'+ ? { headless: true, channel: 'chromium', args: ['--no-sandbox'] }+ : { headless: true });+ const page = await browser.newPage({ viewport: { width, height: 1000 },+ ...(engine === 'webkit' ? { isMobile: true, hasTouch: true } : {}) });+ const errors = [];+ page.on('pageerror', error => errors.push(error.message));+ page.on('console', message => { if (message.type() === 'error') errors.push(message.text()); });+ await page.route(new RegExp(`^http://127\\.0\\.0\\.1:${port}/api/`), route =>+ route.fulfill({ status: 200, contentType: 'application/json', body: '{}' }));+ await page.goto(`http://127.0.0.1:${port}/browser-tests/docs-fragment-navigation.html`,+ { waitUntil: 'domcontentloaded', timeout: 60_000 });+ await page.getByRole('link', { name: '← All documentation' }).click();+ const entry = page.locator('a[data-doc-link][href="/docs/API"]').first();+ if (engine === 'webkit') await entry.tap();+ else {+ await entry.focus();+ await page.keyboard.press('Enter');+ }+ await page.getByRole('heading', { name: 'API Token (Recommended)', exact: true }).waitFor();+ if (tone === 'dark') await page.evaluate(() => document.documentElement.classList.add('dark'));+ const code = page.locator('pre').filter({ hasText: 'pulse_api() (' });+ assert.equal((await code.locator('code').textContent()).trim(), helper);+ assert.ok(helper.includes('--globoff'));+ // Place the changed command line in the viewport, and use the code+ // block's own horizontal scroll on phones rather than overflowing the page.+ await code.evaluate(pre => {+ const style = getComputedStyle(pre.querySelector('code'));+ const line = pre.textContent.split('\n').findIndex(text => text.includes('--globoff'));+ window.scrollTo(0, pre.getBoundingClientRect().top + window.scrollY+ + parseFloat(getComputedStyle(pre).paddingTop) + line * parseFloat(style.lineHeight) - 200);+ if (innerWidth < 500) pre.scrollLeft = pre.scrollWidth;+ });+ assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1));+ const captures = [`${engine}-helper.png`, `${engine}-boundary.png`];+ await page.screenshot({ path: path.join(artifacts, captures[0]) });+ const warning = page.locator('p').filter({ hasText: "shell quotes alone do not disable curl's URL globbing" });+ await warning.scrollIntoViewIfNeeded();+ const text = await warning.innerText();+ for (const phrase of ['{review,ops}', '[1-3]', 'POST, PUT or DELETE',+ 'not as a batch', 'URL-encode', 'does not encode them for you']) {+ assert.ok(text.includes(phrase), phrase);+ }+ assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1));+ await page.screenshot({ path: path.join(artifacts, captures[1]) });+ // Return through the guide's own linked administration help, then use+ // the real renderer's fragment focus/reload handling on the API guide.+ const rbac = page.locator('a[data-doc-link][href^="/docs/RBAC#"]').first();+ await rbac.scrollIntoViewIfNeeded();+ if (engine === 'webkit') await rbac.tap();+ else { await rbac.focus(); await page.keyboard.press('Enter'); }+ await page.waitForURL(`**/docs/RBAC#managing-roles`);+ await page.waitForFunction(() => document.activeElement?.id === 'managing-roles');+ await page.goBack({ waitUntil: 'domcontentloaded' });+ await page.evaluate(() => { window.location.hash = '#api-token-recommended'; });+ await page.waitForFunction(() => document.activeElement?.id === 'api-token-recommended');+ await page.reload({ waitUntil: 'domcontentloaded' });+ await page.waitForFunction(() => document.activeElement?.id === 'api-token-recommended');+ assert.equal((await page.locator('pre').filter({ hasText: 'pulse_api() (' })+ .locator('code').textContent()).trim(), helper);+ assert.deepEqual(errors, []);+ results.push({ engine, browserVersion: browser.version(), width, height: 1000, tone,+ entry: engine === 'webkit' ? 'touch' : 'keyboard', exactRenderedShell: true,+ literalURLAndEncodingBoundary: true, linkedAdminHelp: true,+ fragmentFocusAndReload: true, noPageOverflow: true, captures, errors });+ await browser.close();+ browser = undefined;+ }+ const result = { result: 'passed', verifiedAt: new Date().toISOString(),+ playwrightVersion: require('playwright/package.json').version,+ scope: 'Production Docs/router and exact copied guide; not installed API or customer acceptance',+ docs: { 'frontend-modern/public/docs/API.md': createHash('sha256').update(guide).digest('hex') },+ results };+ fs.writeFileSync(path.join(artifacts, 'result.json'), JSON.stringify(result, null, 2) + '\n');+ console.log(JSON.stringify(result));+ } finally {+ if (browser) await browser.close();+ await server.close();+ }+})().catch(error => { console.error(error); process.exitCode = 1; });diff --git a/frontend-modern/public/docs/API.md b/frontend-modern/public/docs/API.mdindex f736e8ad8e..727ad0f143 100644--- a/frontend-modern/public/docs/API.md+++ b/frontend-modern/public/docs/API.md@@ -84,7 +84,7 @@ pulse_api() (chmod 600 "$auth_file" || exit "$?"result_file=$(mktemp "$auth_dir/api-response.XXXXXX") || exit "$?"curl_exit=0- status=$(curl --disable --fail-with-body --silent --show-error \+ status=$(curl --disable --fail-with-body --silent --show-error --globoff \--proto '=http' --noproxy 127.0.0.1 --connect-timeout 5 --max-time 20 \--header "@$auth_file" --output "$result_file" --write-out '%{http_code}' \"$@" "http://127.0.0.1:7655$api_path") || curl_exit=$?@@ -127,6 +127,13 @@ each administrative change separately and check its current state afterwards.A timeout or incomplete response can occur **after a change was applied**;do not repeat a POST, PUT or DELETE merely because the response was lost.+Keep `--globoff`: shell quotes alone do not disable curl's URL globbing. Without+it, a path containing a brace list such as `{review,ops}` or a range such as+`[1-3]` can send several requests, including several POST, PUT or DELETE+requests. The helper treats these characters literally, not as a batch of+targets. Still quote the whole path in the shell, and URL-encode dynamic resource+IDs and query values; `--globoff` does not encode them for you.+Keep `--disable` first: it ignores local curl configuration that could enabletrace output, bypass TLS or follow redirects. On an authentication-enabledinstance, the protected summary checks token access; `/api/health` is publicdiff --git a/scripts/tests/test_api_auth_docs.py b/scripts/tests/test_api_auth_docs.pyindex c61f713045..7fb1efedb2 100644--- a/scripts/tests/test_api_auth_docs.py+++ b/scripts/tests/test_api_auth_docs.py@@ -387,6 +387,65 @@ class APIAuthDocsTest(unittest.TestCase):self.assertNotIn("Content-Type", headers)self.assertEqual(len(requests), 4)+ def test_shared_helper_keeps_glob_shaped_paths_and_queries_literal(self):+ # One curl process can still send multiple HTTP requests: shell quoting+ # and an argv-count assertion do not prevent curl's own URL expansion.+ paths = (+ "/api/admin/roles/{review,ops}",+ "/api/admin/roles/team[1-3]",+ "/api/audit/actions?resourceId=host[1-3]&limit=10",+ "/api/audit/actions?filter[resource]=host{a,b}",+ )+ self.assert_literal_requests(paths)++ def test_shared_helper_preserves_percent_encoded_identifiers(self):+ self.assert_literal_requests((+ "/api/admin/roles/%7Breview%2Cops%7D%5B1-3%5D",+ "/api/audit/actions?resourceId=host%5B1-3%5D&limit=10",+ ))++ def assert_literal_requests(self, paths):+ with private_recording_server() as (port, requests), tempfile.TemporaryDirectory() as temporary:+ for key, value in (("X-API-Token", TEST_TOKEN), ("Authorization", "Bearer " + TEST_TOKEN)):+ for method in ("GET", "POST", "PUT", "DELETE"):+ for path in paths:+ with self.subTest(header=key, method=method, path=path):+ before = len(requests)+ call = f"pulse_api {method} '{path}' <<'JSON'\n{{\"fixture\":true}}\nJSON\n"+ result = self.run_documented_request(Path(temporary), f"{key}: {value}", port,+ request_helper() + "\n" + call)+ self.assertEqual(len(requests), before + 1,+ "one supplied URL must not expand into multiple requests")+ sent_path, headers, sent_method, body = requests[-1]+ self.assertEqual((sent_method, sent_path), (method, path))+ self.assertEqual(result.returncode, 0, result.stderr.decode())+ self.assertEqual(headers[key], value)+ other_key = "Authorization" if key == "X-API-Token" else "X-API-Token"+ self.assertNotIn(other_key, headers)+ self.assertNotIn("X-Curlrc-Injected", headers)+ if method in ("POST", "PUT"):+ self.assertEqual(headers["Content-Type"], "application/json")+ self.assertEqual(json.loads(body), {"fixture": True})+ else:+ self.assertEqual(body, b"")+ self.assertNotIn("Content-Type", headers)++ def test_glob_shaped_write_fails_privately_without_additional_requests(self):+ for status, partial, expected_exit in ((401, False, 22), (302, False, 1), (200, True, 18)):+ with private_recording_server(status, partial) as (port, requests):+ for method in ("POST", "DELETE"):+ for key, value in (("X-API-Token", TEST_TOKEN), ("Authorization", "Bearer " + TEST_TOKEN)):+ with self.subTest(status=status, method=method, header=key), tempfile.TemporaryDirectory() as temporary:+ before = len(requests)+ path = "/api/admin/roles/{review,ops}"+ call = f"pulse_api {method} '{path}' <<'JSON'\n{{\"fixture\":true}}\nJSON\n"+ result = self.run_documented_request(Path(temporary), f"{key}: {value}", port,+ request_helper() + "\n" + call)+ self.assertEqual(result.returncode, expected_exit, result.stderr.decode())+ self.assertEqual(len(requests), before + 1,+ "failure must not submit another target or retry the write")+ self.assertEqual((requests[-1][2], requests[-1][0]), (method, path))+def test_shared_helper_refuses_unsupported_methods_urls_and_missing_auth_before_transport(self):with recording_server() as (port, requests), tempfile.TemporaryDirectory() as temporary:env = dict(os.environ, HOME=temporary)