Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

fix(e2e): await authenticated bootstrap in cookie-only fixtures

rcourtmanc0c54de76556
diff --cc docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 88e486f844,e655dc19d1..14db19d65e
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@@ -10337,3 -10325,3 +10337,14 @@@ requests and existing access, organizat
`TestContractSSOAmbiguousSavePreservesDetail` and the SSO/RBAC JSON admission
tests establish configuration/account preservation, not installed agent or
guest recovery.
++
++### Browser fixture update budgets
++
++The development-only update API budget in `internal/api/rate_limit_config.go`
++admits aggregate update-banner traffic from isolated browser contexts sharing
++one test-stack IP. Production keeps 60 update requests per minute, while the
++test stack explicitly requests 600. The independent ten-attempt login budget,
++agent report admission, enrollment, credential revocation and installed updater
++contracts remain unchanged. The middleware exhaustion controls in
++`rate_limit_journey_budget_test.go` prove bounded HTTP admission, not an agent
++update, restart or recovery outcome.
diff --cc docs/release-control/v6/internal/subsystems/api-contracts.md
index 8e18b8e8ca,68cbdea54e..cd1648af0d
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@@ -12424,6 -12421,6 +12424,25 @@@ revocation and response payloads are un
ownership controls are in `router_limiter_lifecycle_test.go`; the integration
fixture's cleanup also runs on a failed listener/request assertion.
++### Development browser fixture rate budgets
++
++`internal/api/rate_limit_config.go` owns endpoint-category budgets. Production
++keeps the general API budget at 500 requests per minute and the update budget
++at 60. Only exact `PULSE_DEV=true` admits the explicit
++`PULSE_DEV_GENERAL_API_RATE_LIMIT` and `PULSE_DEV_UPDATE_API_RATE_LIMIT`
++overrides. Each value must be an integer from its production default through
++100000, otherwise the production default applies. These settings never change
++authentication, configuration, recovery or export budgets.
++
++The Core E2E Docker stack sets 5000 general requests and 600 update requests
++per minute because isolated browser contexts share one bridge IP. The real
++update banner continues to fetch plans. The override is finite, retains 429
++and rate-limit headers when exhausted, and does not disable enforcement.
++`rate_limit_config_test.go` covers opt-in and invalid inputs;
++`rate_limit_journey_budget_test.go` exercises the middleware with changing
++cookies at one non-loopback address, including exhaustion and the unchanged
++ten-attempt login budget.
++
### Report-merge undoes operator links
`POST /api/resources/{id}/report-merge` keeps its request, status codes and
diff --cc docs/release-control/v6/internal/subsystems/deployment-installability.md
index cd884b00a9,9b586b1e3f..5bbbf7f4fa
--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md
+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md
@@@ -3016,21 -3015,6 +3016,28 @@@ artifact-selection behaviour
deterministic token authentication after setup, and may use the server setup
API as a fallback only when the UI wizard fails to complete cleanly under the
managed hot-dev runtime.
+ A successful token probe and a protected workspace URL do not establish
- completed browser bootstrap. Token and cookie reuse must wait for the mounted
++ completed browser bootstrap. Token, cookie reuse and password login wait for the mounted
+ authenticated app shell before returning control to a journey, so a pending
+ workspace redirect cannot overwrite its next deep link. Browser rejection
+ remains an authentication failure rather than a reason to accept the URL or
+ retry login. `tests/integration/scripts/fixture-auth.test.mjs` exercises the
+ actual token helper with delayed and rejected bootstrap; the runtime-home
+ onboarding browser contract also holds a real protected-state request.
++ That regression creates and revokes its own token through the admitted
++ session and shared browser-token helper. It must work with cookie-only and
++ primary-token fixtures without replacing their remembered credential.
++ The Core E2E Docker stack explicitly sets bounded development-only general
++ and update request budgets for isolated browser contexts sharing one bridge
++ IP. Production limits and authentication limits remain enforced. The API
++ contracts subsystem owns validation and exhaustion semantics.
+ Settings browser audits scroll the actual application content owner to its
+ observed bottom. Traversal must scale with the populated estate rather than
+ stop after a fixed number of wheel steps. The browser geometry regression
+ `tests/integration/scripts/settings-scroll-audit.test.mjs` retains native
+ Chromium/WebKit traversal of short and 30,000px content plus the positive
+ horizontal-overflow control; the live mobile audit keeps its bottom and
+ overflow assertions.
The built `index.html` must not modulepreload lazy route chunks: the SRI
plugin runs with `preloadDynamicChunks: false` so cold start fetches only the
entry and its static vendor imports (route-level code splitting stays
diff --cc docs/release-control/v6/internal/subsystems/registry.json
index 9453917fe5,0ef63092d2..44b54af4a3
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@@ -3314,6 -3313,6 +3314,20 @@@
"internal/api/router_webhook_cidr_reload_test.go"
]
},
++ {
++ "id": "endpoint-rate-budgets",
++ "label": "endpoint middleware rate budget and isolation proof",
++ "match_prefixes": [],
++ "match_files": [
++ "internal/api/rate_limit_config.go"
++ ],
++ "allow_same_subsystem_tests": false,
++ "test_prefixes": [],
++ "exact_files": [
++ "internal/api/rate_limit_config_test.go",
++ "internal/api/rate_limit_journey_budget_test.go"
++ ]
++ },
{
"id": "backend-payload-contracts",
"label": "backend API payload proof",
diff --cc docs/release-control/v6/internal/subsystems/storage-recovery.md
index 927fca8095,c4b457fcd4..4bbef90025
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@@ -7297,3 -7293,3 +7297,14 @@@ reset. `TestContractSSOAmbiguousSavePre
admission tests preserve persisted settings, exact roles and token usability.
No database schema, stored history, backup/thaw operation or native recovery
route changes; parser admission does not establish those operational outcomes.
++
++### Browser fixture update budgets
++
++The Core E2E stack explicitly opts into a finite development update API budget
++so isolated browser sessions at one bridge IP can read the real update plan.
++`internal/api/rate_limit_config.go` keeps production at 60 update requests per
++minute and requires exact development mode plus a valid bounded override.
++`rate_limit_journey_budget_test.go` verifies exhaustion and unchanged login
++admission. This changes no storage history, backup, restore, migration or
++recovery contract. Request admission does not qualify stored-data preservation
++or a successful upgrade/recovery operation.
diff --cc internal/api/rate_limit_config.go
index 1ddbc3f55d,1ddbc3f55d..ca50a5f726
--- a/internal/api/rate_limit_config.go
+++ b/internal/api/rate_limit_config.go
@@@ -10,7 -10,7 +10,8 @@@ import
const (
defaultGeneralAPIRateLimit = 500
-- maxDevGeneralAPIRateLimit = 100000
++ defaultUpdateAPIRateLimit = 60
++ maxDevAPIRateLimit = 100000
)
// EndpointRateLimitConfig defines rate limiting configuration for different endpoint categories
@@@ -42,7 -42,7 +43,7 @@@ func newEndpointRateLimitConfig() *Endp
RecoveryEndpoints: NewRateLimiter(3, 10*time.Minute), // 3 attempts per 10 minutes
// Update operations: allow frequent polling during updates
-- UpdateEndpoints: NewRateLimiter(60, 1*time.Minute), // 60 checks per minute (modal polls every 2s)
++ UpdateEndpoints: NewRateLimiter(developmentAPIRateLimit("PULSE_DEV_UPDATE_API_RATE_LIMIT", defaultUpdateAPIRateLimit), 1*time.Minute),
// WebSocket connections: per-connection limits
WebSocketEndpoints: NewRateLimiter(30, 1*time.Minute), // 30 new connections per minute
@@@ -73,13 -73,13 +74,19 @@@ func (cfg *EndpointRateLimitConfig) Sto
}
func generalAPIRateLimit() int {
++ return developmentAPIRateLimit("PULSE_DEV_GENERAL_API_RATE_LIMIT", defaultGeneralAPIRateLimit)
++}
++
++// Isolated browser contexts share one Docker bridge IP. Explicit development
++// budgets admit that aggregate traffic while retaining finite enforcement.
++func developmentAPIRateLimit(variable string, productionLimit int) int {
if os.Getenv("PULSE_DEV") != "true" {
-- return defaultGeneralAPIRateLimit
++ return productionLimit
}
-- configured, err := strconv.Atoi(strings.TrimSpace(os.Getenv("PULSE_DEV_GENERAL_API_RATE_LIMIT")))
-- if err != nil || configured < defaultGeneralAPIRateLimit || configured > maxDevGeneralAPIRateLimit {
-- return defaultGeneralAPIRateLimit
++ configured, err := strconv.Atoi(strings.TrimSpace(os.Getenv(variable)))
++ if err != nil || configured < productionLimit || configured > maxDevAPIRateLimit {
++ return productionLimit
}
return configured
}
diff --cc internal/api/rate_limit_config_test.go
index d968f4a266,d968f4a266..00ce97cc6e
--- a/internal/api/rate_limit_config_test.go
+++ b/internal/api/rate_limit_config_test.go
@@@ -33,6 -33,6 +33,36 @@@ func TestGeneralAPIRateLimitDevelopment
}
}
++func TestUpdateAPIRateLimitDevelopmentOverride(t *testing.T) {
++ tests := []struct {
++ name, devMode, configured string
++ want int
++ }{
++ {name: "default", want: 60},
++ {name: "production ignores override", configured: "600", want: 60},
++ {name: "development requires explicit update override", devMode: "true", want: 60},
++ {name: "development accepts bounded override", devMode: "true", configured: "600", want: 600},
++ {name: "development rejects lower limit", devMode: "true", configured: "59", want: 60},
++ {name: "development rejects excessive limit", devMode: "true", configured: "100001", want: 60},
++ {name: "development rejects malformed limit", devMode: "true", configured: "many", want: 60},
++ }
++ for _, tt := range tests {
++ t.Run(tt.name, func(t *testing.T) {
++ t.Setenv("PULSE_DEV", tt.devMode)
++ t.Setenv("PULSE_DEV_GENERAL_API_RATE_LIMIT", "5000")
++ t.Setenv("PULSE_DEV_UPDATE_API_RATE_LIMIT", tt.configured)
++ cfg := newEndpointRateLimitConfig()
++ t.Cleanup(cfg.Stop)
++ if cfg.UpdateEndpoints.limit != tt.want {
++ t.Fatalf("update budget = %d, want %d", cfg.UpdateEndpoints.limit, tt.want)
++ }
++ if cfg.AuthEndpoints.limit != 10 || cfg.ConfigEndpoints.limit != 30 {
++ t.Fatal("update override changed an independent endpoint budget")
++ }
++ })
++ }
++}
++
func TestGetRateLimiterForEndpoint(t *testing.T) {
isolateRateLimitFixture(t)
// Ensure rate limiters are initialized
diff --cc internal/api/rate_limit_journey_budget_test.go
index f658b902d8,f658b902d8..c0f1d16a92
--- a/internal/api/rate_limit_journey_budget_test.go
+++ b/internal/api/rate_limit_journey_budget_test.go
@@@ -63,3 -63,3 +63,60 @@@ func TestJourneyGeneralAPIBudgetIsolati
})
}
}
++
++// Independent browser contexts share the Docker bridge address. Their update
++// banners must not consume one another's explicitly configured dev budget.
++func TestJourneyUpdateAPIBudgetIsolation(t *testing.T) {
++ for _, tc := range []struct {
++ name, dev, configured string
++ limit int
++ }{
++ {"production retains enforcement", "", "600", 60},
++ {"development retains default without opt-in", "true", "", 60},
++ {"development harness remains bounded", "true", "600", 600},
++ } {
++ t.Run(tc.name, func(t *testing.T) {
++ t.Setenv("PULSE_DEV", tc.dev)
++ t.Setenv("PULSE_DEV_GENERAL_API_RATE_LIMIT", "")
++ t.Setenv("PULSE_DEV_UPDATE_API_RATE_LIMIT", tc.configured)
++ cfg := newEndpointRateLimitConfig()
++ t.Cleanup(cfg.Stop)
++ handler := UniversalRateLimitMiddlewareWithConfig(cfg, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
++ w.WriteHeader(http.StatusNoContent)
++ }))
++ request := func(endpoint, method string, n int) *httptest.ResponseRecorder {
++ r := httptest.NewRequest(method, endpoint, nil)
++ r.RemoteAddr = "192.0.2.17:12345"
++ r.AddCookie(&http.Cookie{Name: "pulse_session", Value: "synthetic-" + strconv.Itoa(n)})
++ w := httptest.NewRecorder()
++ handler.ServeHTTP(w, r)
++ return w
++ }
++ endpoints := []string{"/api/updates/plan?version=99.1.0-rc.1", "/api/updates/check"}
++ for i := 0; i < tc.limit; i++ {
++ if w := request(endpoints[i%2], http.MethodGet, i); w.Code != http.StatusNoContent {
++ t.Fatalf("request %d: status %d, want 204", i+1, w.Code)
++ }
++ }
++ for _, endpoint := range endpoints {
++ w := request(endpoint, http.MethodGet, tc.limit)
++ if w.Code != http.StatusTooManyRequests || w.Header().Get("Retry-After") != "60" ||
++ w.Header().Get("X-RateLimit-Limit") != strconv.Itoa(tc.limit) {
++ t.Fatalf("exhausted %s: status %d, headers %v", endpoint, w.Code, w.Header())
++ }
++ }
++ if cfg.GeneralAPI.limit != 500 {
++ t.Fatal("update override changed the general API budget")
++ }
++ for i := 0; i < 11; i++ {
++ want := http.StatusNoContent
++ if i == 10 {
++ want = http.StatusTooManyRequests
++ }
++ if w := request("/api/login", http.MethodPost, i); w.Code != want {
++ t.Fatalf("login request %d: status %d, want %d", i+1, w.Code, want)
++ }
++ }
++ })
++ }
++}
diff --cc scripts/release_control/canonical_completion_guard_test.py
index d73d22addf,aeec26d7d4..3d61bd6e41
--- a/scripts/release_control/canonical_completion_guard_test.py
+++ b/scripts/release_control/canonical_completion_guard_test.py
@@@ -2045,6 -2043,6 +2045,18 @@@ class CanonicalCompletionGuardTest(unit
],
)
++ def test_endpoint_budget_change_requires_its_middleware_controls(self):
++ required = infer_impacted_subsystems(["internal/api/rate_limit_config.go"])
++ self.assertEqual(set(required), {"api-contracts"})
++ requirement = required["api-contracts"]["verification_requirements"][0]
++ self.assertEqual(requirement["id"], "endpoint-rate-budgets")
++ self.assertEqual(requirement["test_prefixes"], [])
++ self.assertFalse(requirement["allow_same_subsystem_tests"])
++ self.assertEqual(requirement["exact_files"], [
++ "internal/api/rate_limit_config_test.go",
++ "internal/api/rate_limit_journey_budget_test.go",
++ ])
++
def test_session_store_change_uses_session_migration_proof_policy(self):
required = infer_impacted_subsystems(["internal/api/session_store.go"])
self.assertEqual(set(required), {"api-contracts"})
diff --cc scripts/release_control/subsystem_lookup_test.py
index fbe6468ac1,d256326bc8..c717473253
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@@ -1297,6 -1297,6 +1297,18 @@@ class SubsystemLookupTest(unittest.Test
],
)
++ def test_endpoint_budget_lookup_uses_middleware_proofs(self) -> None:
++ result = lookup_paths(["internal/api/rate_limit_config.go"])
++ self.assertEqual(result["unowned_runtime_files"], [])
++ matches = result["files"][0]["matches"]
++ self.assertEqual([entry["subsystem"] for entry in matches], ["api-contracts"])
++ requirement = matches[0]["verification_requirement"]
++ self.assertEqual(requirement["id"], "endpoint-rate-budgets")
++ self.assertEqual(requirement["exact_files"], [
++ "internal/api/rate_limit_config_test.go",
++ "internal/api/rate_limit_journey_budget_test.go",
++ ])
++
def test_lookup_paths_accepts_docker_action_api_proofs(self) -> None:
result = lookup_paths(["internal/api/docker_container_action_executor.go"])
self.assertEqual(result["unowned_runtime_files"], [])
diff --cc scripts/tests/test_e2e_test_images.py
index c8364dc620,c8364dc620..8af9ca87f3
--- a/scripts/tests/test_e2e_test_images.py
+++ b/scripts/tests/test_e2e_test_images.py
@@@ -255,6 -255,6 +255,19 @@@ class E2EImageBundleTest(unittest.TestC
class E2EImageWorkflowTest(unittest.TestCase):
++ def test_browser_fixture_budgets_are_explicit_bounded_and_dev_only(self):
++ source = IMAGES.COMPOSE.read_text().split("\n pulse-test:\n", 1)[1]
++ source = source.split("\nvolumes:\n", 1)[0]
++ environment = dict(re.findall(r"(?m)^\s+- (PULSE_DEV[A-Z_]*)=([^\n]+)$", source))
++ self.assertEqual(environment["PULSE_DEV"], "true")
++ for name, production_limit in (("PULSE_DEV_GENERAL_API_RATE_LIMIT", 500),
++ ("PULSE_DEV_UPDATE_API_RATE_LIMIT", 60)):
++ with self.subTest(variable=name):
++ configured = int(environment[name])
++ self.assertGreater(configured, production_limit)
++ self.assertLessEqual(configured, 100000)
++ self.assertNotIn(name, (ROOT / "docker-compose.yml").read_text())
++
def assert_fixture_admission(self, workflow):
consumer = job_block(workflow, "e2e")
image_admission = consumer.index("- name: Admit the source-bound test images")
diff --cc tests/integration/docker-compose.test.yml
index c536d6926b,c536d6926b..fa75e4ff52
--- a/tests/integration/docker-compose.test.yml
+++ b/tests/integration/docker-compose.test.yml
@@@ -92,6 -92,6 +92,10 @@@ services
# Keep production's universal limit intact while preventing that synthetic
# aggregation from starving later tests in this development-only stack.
- PULSE_DEV_GENERAL_API_RATE_LIMIT=5000
++ # Each isolated browser also mounts the real update banner. Keep its
++ # shared-IP plan/check traffic bounded without exhausting the production
++ # 60-request budget during a shard's repeated document bootstraps.
++ - PULSE_DEV_UPDATE_API_RATE_LIMIT=600
- PULSE_MULTI_TENANT_ENABLED=${PULSE_MULTI_TENANT_ENABLED:-false}
- PULSE_ALLOW_DOCKER_UPDATES=true
- PULSE_UPDATE_STAGE_DELAY_MS=250
diff --cc tests/integration/scripts/fixture-auth.test.mjs
index 4b2bbb0115,848a9b58e2..0469d942fd
--- a/tests/integration/scripts/fixture-auth.test.mjs
+++ b/tests/integration/scripts/fixture-auth.test.mjs
@@@ -294,75 -294,6 +294,115 @@@ test('primary-token fixtures keep thei
assert.equal((await page.context().cookies()).length, 0);
});
- function primaryBootstrapFixture({ rejected = false } = {}) {
++function primaryBootstrapFixture({ rejected = false, passwordLogin = false } = {}) {
++ const rememberedTokens = [];
+ let currentURL = 'about:blank';
+ let releaseBootstrap;
+ const bootstrap = new Promise(resolve => { releaseBootstrap = resolve; });
+ let notifyWaitStarted;
+ const waitStarted = new Promise(resolve => { notifyWaitStarted = resolve; });
+ let ready = false;
++ let submitted = false;
+ const page = {
+ goto: async target => { currentURL = new URL(target, 'http://127.0.0.1:7655').href; },
+ url: () => currentURL,
- waitForURL: async () => { currentURL = 'http://127.0.0.1:7655/infrastructure'; },
- locator: () => ({ waitFor: () => new Promise(() => {}) }),
++ waitForURL: async () => {
++ if (passwordLogin && !submitted) return new Promise(() => {});
++ currentURL = 'http://127.0.0.1:7655/infrastructure';
++ },
++ locator: () => ({
++ waitFor: () => passwordLogin && !submitted ? Promise.resolve() : new Promise(() => {}),
++ first() { return this; },
++ isVisible: async () => false,
++ }),
++ fill: async () => {},
++ click: async () => { submitted = true; currentURL = 'http://127.0.0.1:7655/infrastructure'; },
++ waitForResponse: async () => response(200),
+ waitForFunction: async predicate => {
+ const evaluate = () => runInNewContext(`(${predicate.toString()})()`, {
+ document: { querySelector: selector => {
+ if (!ready) return null;
+ const present = selector === '.app-scroll-shell' ? !rejected : rejected;
+ return present ? { getClientRects: () => [1] } : null;
+ } },
+ getComputedStyle: () => ({ visibility: 'visible' }),
+ });
+ assert.equal(evaluate(), false, 'protected bootstrap is still loading');
+ notifyWaitStarted();
+ await bootstrap;
+ return { jsonValue: async () => evaluate(), dispose: async () => {} };
+ },
+ };
- const authenticate = runInNewContext(stripTypeScriptTypes([
++ const { authenticate, authenticateExplicit, login } = runInNewContext(stripTypeScriptTypes([
+ source.match(/const AUTHENTICATED_URL =[\s\S]*?;\n/)[0],
+ fragment('async function waitForAuthenticatedAppShell(', 'export async function waitForPulseReady('),
- fragment('async function authenticateWithPrimaryAPIToken(', 'export async function ensureAuthenticated('),
- 'authenticateWithPrimaryAPIToken;',
++ fragment('export async function login(', 'export async function authenticateWithAPIToken('),
++ fragment('export async function authenticateWithAPIToken(', 'export async function ensureAuthenticated('),
++ '({ authenticate: authenticateWithPrimaryAPIToken, authenticateExplicit: authenticateWithAPIToken, login });',
+ ].join('\n')), {
+ URL, encodeURIComponent,
+ primaryAPITokenCandidates: () => [{ token: 'fixture-token' }],
+ apiRequest: async () => response(200),
- rememberPrimaryAPIToken: () => {},
++ rememberPrimaryAPIToken: token => { rememberedTokens.push(token); },
+ waitForAppShell: async () => {},
+ });
+ return {
- page, authenticate, waitStarted,
++ page, authenticate, authenticateExplicit, login, rememberedTokens, waitStarted,
+ completeBootstrap: () => {
+ ready = true;
+ currentURL = 'http://127.0.0.1:7655/proxmox/overview';
+ releaseBootstrap();
+ },
+ };
+}
+
+test('an admitted token and workspace URL cannot race a subsequent onboarding navigation', async () => {
+ const f = primaryBootstrapFixture();
+ let completed = false;
+ const authentication = f.authenticate(f.page).then(value => { completed = true; return value; });
+ await Promise.race([f.waitStarted, authentication]);
+ assert.equal(completed, false, 'token auth must wait for the mounted authenticated shell');
+ f.completeBootstrap();
+ assert.equal(await authentication, true);
+ await f.page.goto('/settings/infrastructure?add=agent');
+ assert.equal(f.page.url(), 'http://127.0.0.1:7655/settings/infrastructure?add=agent');
+});
+
+test('a valid token probe cannot hide a rejected browser bootstrap', async () => {
+ const f = primaryBootstrapFixture({ rejected: true });
+ const authentication = f.authenticate(f.page);
+ await Promise.race([f.waitStarted, authentication]);
+ f.completeBootstrap();
+ await assert.rejects(authentication, /Session was rejected by browser bootstrap/);
+});
+
++test('a test-owned token waits for bootstrap without replacing the primary fixture credential', async () => {
++ const f = primaryBootstrapFixture();
++ let completed = false;
++ const authentication = f.authenticateExplicit(f.page, 'test-owned-token').then(value => {
++ completed = true;
++ return value;
++ });
++ await Promise.race([f.waitStarted, authentication]);
++ assert.equal(completed, false);
++ f.completeBootstrap();
++ assert.equal(await authentication, true);
++ assert.deepEqual(f.rememberedTokens, []);
++});
++
++for (const passwordLogin of [false, true]) {
++ test(`${passwordLogin ? 'a submitted password' : 'an existing cookie'} login waits for mounted browser bootstrap`, async () => {
++ const f = primaryBootstrapFixture({ passwordLogin });
++ let completed = false;
++ const authentication = f.login(f.page, { username: 'fixture', password: 'fixture' }).then(() => { completed = true; });
++ await Promise.race([f.waitStarted, authentication]);
++ assert.equal(completed, false, 'a workspace URL alone must not finish login');
++ f.completeBootstrap();
++ await authentication;
++ assert.equal(completed, true);
++ });
++}
++
test('explicit session fixtures still get independent password sessions', async t => {
const f = fixture(t, { tokenAuth: true });
f.save([cookie('pulse_session', 'saved-live')]);
diff --cc tests/integration/tests/11-first-session.spec.ts
index 1f4e162e2f,1f4e162e2f..dbec0c6b11
--- a/tests/integration/tests/11-first-session.spec.ts
+++ b/tests/integration/tests/11-first-session.spec.ts
@@@ -285,16 -285,16 +285,40 @@@ test.describe.serial("First-session exp
route: "/settings/support/reporting",
expectedURL: /\/settings\/support\/reporting/,
feature: "advanced_reporting",
-- paywallIndicator: /Advanced Reporting/i,
++ paywallIndicator: /Advanced Reporting|Pulse Pro runtime required/i,
},
{
route: "/settings/security-webhooks",
expectedURL: /\/settings\/security-webhooks/,
feature: "audit_logging",
-- paywallIndicator: /Audit (Logging|Webhooks)/i,
++ paywallIndicator: /Audit (Logging|Webhooks)|Pulse Pro runtime required/i,
},
] as const;
++ await page.addInitScript(() => {
++ (window as any).__pulseFlashDetected = false;
++ const selector =
++ '[data-settings-content] form input:not([type="search"]), [data-settings-content] form textarea, [data-settings-content] form select';
++ const checkForFlash = () => {
++ const visible = Array.from(document.querySelectorAll(selector)).some(
++ element => element.getClientRects().length > 0 && getComputedStyle(element).visibility !== "hidden",
++ );
++ if (visible) {
++ (window as any).__pulseFlashDetected = true;
++ }
++ };
++ const observer = new MutationObserver(checkForFlash);
++ (window as any).__pulseFlashObserver = observer;
++ // Document exists before documentElement, including at init-script time.
++ // Scope detection to the gated panel so sign-in controls are not mistaken
++ // for unlocked licensed content.
++ observer.observe(document, {
++ childList: true, subtree: true, attributes: true,
++ attributeFilter: ["class", "style", "hidden"],
++ });
++ checkForFlash();
++ });
++
try {
for (const {
route,
@@@ -305,65 -305,65 +329,27 @@@
const hasFeature = features.has(feature);
if (!hasFeature) {
-- // Install a MutationObserver via addInitScript BEFORE navigating so it
-- // runs before any app code. This catches transient form elements that
-- // flash before the paywall renders (flash-of-unlocked-content).
-- await page.addInitScript(() => {
-- (window as any).__pulseFlashDetected = false;
-- const SELECTOR =
-- 'form input:not([type="search"]), form textarea, form select';
--
-- const checkForFlash = () => {
-- const els = document.querySelectorAll(SELECTOR);
-- if (els.length > 0) {
-- (window as any).__pulseFlashDetected = true;
-- }
-- };
--
-- const observer = new MutationObserver(checkForFlash);
--
-- // Start observing on documentElement immediately (always available
-- // in addInitScript context), so we catch body insertion and all
-- // subsequent DOM mutations including app boot. This avoids the gap
-- // where DOMContentLoaded fires after app scripts.
-- observer.observe(document.documentElement, {
-- childList: true,
-- subtree: true,
-- });
-- // Also do an immediate check in case DOM is already populated.
-- checkForFlash();
--
-- // Auto-disconnect after 5 seconds to avoid leaking.
-- setTimeout(() => observer.disconnect(), 5000);
-- });
--
await page.goto(route, { waitUntil: "domcontentloaded" });
await page.waitForURL(expectedURL, { timeout: 10_000 });
await expect(page.locator("#root")).toBeVisible();
-- // Wait for the page to settle, then read the observer result.
-- await page.waitForTimeout(2_000);
-- const flashDetected = await page.evaluate(
-- () => (window as any).__pulseFlashDetected === true,
-- );
--
++ const paywallIndicator = page
++ .getByRole("main")
++ .getByRole("heading", { level: 4, name: paywallPattern });
++ await expect(
++ paywallIndicator,
++ `Gated route ${route} (feature=${feature}) should show its gate when unavailable`,
++ ).toBeVisible({ timeout: 5_000 });
++
++ // Observe through actual gate readiness, including a slow bootstrap.
++ const flashDetected = await page.evaluate(() => {
++ (window as any).__pulseFlashObserver?.disconnect();
++ return (window as any).__pulseFlashDetected === true;
++ });
expect(
flashDetected,
`Gated route ${route} (feature=${feature}) showed form elements on unlicensed tier (flash-of-unlocked-content)`,
).toBe(false);
--
-- // Paywall indicator should be visible.
-- const paywallIndicator = page
-- .getByRole("main")
-- .getByText(paywallPattern)
-- .first();
-- const isPaywallVisible = await paywallIndicator
-- .isVisible({ timeout: 5_000 })
-- .catch(() => false);
-- expect(
-- isPaywallVisible,
-- `Gated route ${route} (feature=${feature}) should show paywall when feature is not available`,
-- ).toBeTruthy();
} else {
await page.goto(route, { waitUntil: "domcontentloaded" });
await page.waitForURL(expectedURL, { timeout: 10_000 });
diff --cc tests/integration/tests/62-runtime-home-onboarding-contract.spec.ts
index ec6d45c862,aacad89836..876ae6b549
--- a/tests/integration/tests/62-runtime-home-onboarding-contract.spec.ts
+++ b/tests/integration/tests/62-runtime-home-onboarding-contract.spec.ts
@@@ -4,7 -4,6 +4,8 @@@ import { fileURLToPath } from "node:url
import { test as base, expect } from "@playwright/test";
import {
createAuthenticatedStorageState,
- E2E_CREDENTIALS,
++ apiRequest,
++ authenticateWithAPIToken,
ensureAuthenticated,
} from "./helpers";
@@@ -107,47 -106,6 +108,58 @@@ test.describe("runtime-home onboarding
).toHaveCount(0);
});
+ test("waits for token bootstrap before navigating to the agent install handoff", async ({ page }) => {
+ await ensureAuthenticated(page);
- expect(E2E_CREDENTIALS.primaryApiToken, "the runtime fixture must retain its primary token").toBeTruthy();
++ const created = await apiRequest(page, "/api/security/tokens", {
++ method: "POST",
++ data: { name: "E2E browser bootstrap regression", scopes: ["*"] },
++ });
++ expect(created.ok()).toBeTruthy();
++ const { token, record } = await created.json() as { token: string; record: { id: string } };
++ expect(token).toBeTruthy();
++ expect(record.id).toBeTruthy();
+ let tokenNavigationStarted = false;
+ const onNavigation = () => {
+ if (new URL(page.url()).searchParams.has("token")) tokenNavigationStarted = true;
+ };
- page.on("framenavigated", onNavigation);
+ let releaseBootstrap!: () => void;
+ const bootstrapHold = new Promise<void>(resolve => { releaseBootstrap = resolve; });
+ let notifyBlocked!: () => void;
+ const blocked = new Promise<void>(resolve => { notifyBlocked = resolve; });
+ const holdState = async (route: import("@playwright/test").Route) => {
+ if (tokenNavigationStarted) {
+ notifyBlocked();
+ await bootstrapHold;
+ }
+ await route.continue();
+ };
- await page.route("**/api/state/summary", holdState);
- let authentication: Promise<void> | undefined;
++ let authentication: Promise<boolean> | undefined;
+ try {
++ page.on("framenavigated", onNavigation);
++ await page.route("**/api/state/summary", holdState);
+ let completed = false;
- authentication = ensureAuthenticated(page).then(() => { completed = true; });
++ authentication = authenticateWithAPIToken(page, token).then(result => { completed = true; return result; });
+ await Promise.race([blocked, authentication]);
+ expect(completed, "token authentication must await protected browser bootstrap").toBe(false);
+ releaseBootstrap();
- await authentication;
++ expect(await authentication).toBe(true);
+ await page.goto("/settings/infrastructure?add=agent", { waitUntil: "domcontentloaded" });
+ await expect(page).toHaveURL(/\/settings\/infrastructure\?add=agent$/);
+ await expect(page.getByRole("dialog").getByRole("heading", {
+ name: "Add Pulse Agent", exact: true,
+ })).toBeVisible();
+ } finally {
+ releaseBootstrap();
+ await authentication?.catch(() => {});
+ await page.unroute("**/api/state/summary", holdState);
+ page.off("framenavigated", onNavigation);
++ const revoked = await apiRequest(page, `/api/security/tokens/${encodeURIComponent(record.id)}`, {
++ method: "DELETE",
++ });
++ expect(revoked.ok(), "the test-owned bootstrap token must be revoked").toBeTruthy();
+ }
+ });
+
test("retires legacy platform-management paths to the not-found page", async ({
page,
}) => {
diff --cc tests/integration/tests/62-storage-growth-column.spec.ts
index 5c089b35b6,5c089b35b6..a3f20626dd
--- a/tests/integration/tests/62-storage-growth-column.spec.ts
+++ b/tests/integration/tests/62-storage-growth-column.spec.ts
@@@ -137,7 -137,7 +137,7 @@@ async function firstVisibleGrowthRow
// The retired /storage page paired the Growth column with a 1h/7d range
// switch; on /proxmox/storage the column is fixed to a 24h window (the header
--// is a sort control, not a range control). The proof: the rendered Growth
++// labels that fixed window). The proof: the rendered Growth
// (24h) label for a pool matches the delta derived from the same 24h
// used-capacity history the /api/storage-charts endpoint serves.
test.describe.serial('Storage growth column', () => {
@@@ -158,9 -158,9 +158,9 @@@
await page.goto('/proxmox/storage', { waitUntil: 'domcontentloaded' });
await expect(page).toHaveURL(/\/proxmox\/storage/);
await expect(page.getByTestId('storage-page')).toBeVisible({ timeout: 60_000 });
-- await expect(
-- page.getByRole('button', { name: 'Sort Growth (24h) column' }).first(),
-- ).toBeVisible();
++ const growthHeader = page.locator('thead [data-storage-column="growth"]');
++ await expect(growthHeader).toBeVisible();
++ await expect(growthHeader).toHaveAttribute('aria-label', 'Growth (24h)');
await expect(page.locator('tr[data-summary-series-id]').first()).toBeVisible({
timeout: 30_000,
});
diff --cc tests/integration/tests/64-workloads-proxmox-refresh-stability.spec.ts
index 5163227a2e,5ce67d63e5..9b43754ba4
--- a/tests/integration/tests/64-workloads-proxmox-refresh-stability.spec.ts
+++ b/tests/integration/tests/64-workloads-proxmox-refresh-stability.spec.ts
@@@ -285,6 -285,6 +285,7 @@@ test.describe.serial("Workloads Proxmo
let staleProjectionResponses = 0;
let deletionResponses = 0;
let publishDeletion = false;
++ const retainedGuest = issue1611Container(102, "lxc-beta", "online", true);
// The Proxmox surface owns a source-scoped canonical resource snapshot.
// Intercept that REST sequence and prevent live inventory frames from
@@@ -308,21 -308,21 +309,21 @@@
if (workloadRequests === 1) {
data = [
issue1611Container(101, "lxc-alpha", "online"),
-- issue1611Container(102, "lxc-beta", "online", true),
++ retainedGuest,
issue1611Container(103, "lxc-gamma", "online"),
];
} else if (!publishDeletion) {
staleProjectionResponses += 1;
data = [
issue1611Container(101, "lxc-alpha", "warning"),
-- issue1611Container(102, "lxc-beta", "online", true),
++ retainedGuest,
issue1611Container(103, "lxc-gamma", "warning"),
];
} else {
deletionResponses += 1;
data = [
issue1611Container(101, "lxc-alpha", "online"),
-- issue1611Container(102, "lxc-beta", "online", true),
++ retainedGuest,
];
}
@@@ -349,7 -349,7 +350,7 @@@
const retainedRow = rows.filter({ hasText: "lxc-beta" });
await retainedRow.click();
const detailRow = page.locator(
-- 'tr[data-inline-detail-for="lab:node-a:102"]',
++ `tr[data-inline-detail-for=${JSON.stringify(retainedGuest.id)}]`,
);
await expect(detailRow).toBeVisible();
@@@ -357,12 -357,12 +358,13 @@@
// frames rather than a timer-driven REST poll. Use the same forced
// canonical refresh event as an in-app metadata update so this remains a
// deterministic snapshot-reconciliation proof with WebSockets blocked.
-- await page.evaluate(() =>
++ await page.evaluate((metadataId) =>
window.dispatchEvent(
new CustomEvent("pulse:resource-metadata-changed", {
-- detail: { metadataKind: "guest", metadataId: "lab:node-a:102" },
++ detail: { metadataKind: "guest", metadataId },
}),
),
++ retainedGuest.id,
);
await expect
.poll(() => staleProjectionResponses, { timeout: 15_000 })
@@@ -373,12 -373,12 +375,13 @@@
await expect(detailRow).toBeVisible();
publishDeletion = true;
-- await page.evaluate(() =>
++ await page.evaluate((metadataId) =>
window.dispatchEvent(
new CustomEvent("pulse:resource-metadata-changed", {
-- detail: { metadataKind: "guest", metadataId: "lab:node-a:102" },
++ detail: { metadataKind: "guest", metadataId },
}),
),
++ retainedGuest.id,
);
await expect
.poll(() => deletionResponses, { timeout: 15_000 })
diff --cc tests/integration/tests/79-update-flow.spec.ts
index 85653b9f96,95b2cad480..d313411fa8
--- a/tests/integration/tests/79-update-flow.spec.ts
+++ b/tests/integration/tests/79-update-flow.spec.ts
@@@ -17,8 -17,8 +17,31 @@@
* release (e.g. managed local backend without PULSE_UPDATE_SERVER).
*/
--import { expect, test, type Page } from "@playwright/test";
- import { apiRequest } from "./helpers";
-import { apiRequest, ensureAuthenticated } from "./helpers";
++import fs from "node:fs";
++import path from "node:path";
++import { fileURLToPath } from "node:url";
++import { expect, test as base, type Page } from "@playwright/test";
++import { apiRequest, createAuthenticatedStorageState } from "./helpers";
++
++const __dirname = path.dirname(fileURLToPath(import.meta.url));
++const test = base.extend<{}, { authStorageStatePath: string }>({
++ storageState: async ({ authStorageStatePath }, use) => {
++ await use(authStorageStatePath);
++ },
++ authStorageStatePath: [async ({ browser }, use, workerInfo) => {
++ const storageStatePath = path.resolve(
++ __dirname, "..", "..", "tmp", "playwright-auth",
++ `update-flow-${workerInfo.project.name}.json`,
++ );
++ fs.mkdirSync(path.dirname(storageStatePath), { recursive: true });
++ await createAuthenticatedStorageState(browser, storageStatePath);
++ try {
++ await use(storageStatePath);
++ } finally {
++ fs.rmSync(storageStatePath, { force: true });
++ }
++ }, { scope: "worker" }],
++});
const MOCK_STABLE_VERSION = "99.0.0";
const MOCK_RC_VERSION = "99.1.0-rc.1";
@@@ -63,14 -63,15 +86,14 @@@ async function fetchUpdateStatus(page:
test.describe.serial("update flow against the mock update server", () => {
test.beforeEach(async ({ page }) => {
- // This is an API contract. apiRequest carries the admitted primary token
- // without mounting a dashboard and starting unrelated update polling for
- // every case in the serial flow.
- await ensureAuthenticated(page);
++ // Bootstrap one admitted cookie session per worker, including when CI
++ // retains no primary token. Individual API cases inherit it without
++ // mounting a dashboard and starting unrelated update polling each time.
if (mockUpdateServerWired === null) {
const res = await apiRequest(page, "/api/updates/check?channel=stable");
- if (!res.ok()) {
- mockUpdateServerWired = false;
- } else {
- const info = (await res.json()) as UpdateInfo;
- mockUpdateServerWired = info.latestVersion === MOCK_STABLE_VERSION;
- }
+ expect(res.ok(), await res.text()).toBeTruthy();
+ const info = (await res.json()) as UpdateInfo;
+ mockUpdateServerWired = info.latestVersion === MOCK_STABLE_VERSION;
}
test.skip(
!mockUpdateServerWired,
diff --cc tests/integration/tests/helpers.ts
index 9f764329b8,c0dcea65b6..9586e3acb0
--- a/tests/integration/tests/helpers.ts
+++ b/tests/integration/tests/helpers.ts
@@@ -931,6 -931,6 +931,7 @@@ export async function loginAsAdmin(page
// Wait for redirect to the authenticated application shell.
await page.waitForURL(/\/(infrastructure|nodes|proxmox)/);
++ await waitForAuthenticatedAppShell(page);
}
export async function login(page: Page, credentials = E2E_CREDENTIALS) {
@@@ -951,6 -951,6 +952,7 @@@
]);
if (state === "authenticated") {
++ await waitForAuthenticatedAppShell(page);
return;
}
@@@ -987,6 -987,6 +989,7 @@@
const deadline = Date.now() + 30_000;
while (Date.now() < deadline) {
if (AUTHENTICATED_URL.test(page.url())) {
++ await waitForAuthenticatedAppShell(page);
return "authenticated";
}
const loginErrorVisible = await loginErrorText
@@@ -1049,6 -1049,6 +1052,7 @@@
await page.waitForTimeout(backoffMs);
const retryState = await prepareFreshLoginAttempt();
if (retryState === "authenticated") {
++ await waitForAuthenticatedAppShell(page);
return;
}
if (retryState !== "login") {
@@@ -1062,6 -1062,6 +1066,43 @@@
throw new Error(`Login failed: ${lastOutcome}`);
}
++// Both configured primary-token fixtures and tests with their own short-lived
++// token share this browser bootstrap boundary. Explicit tokens do not replace
++// the fixture's remembered primary credential.
++export async function authenticateWithAPIToken(page: Page, token: string): Promise<boolean> {
++ await page.goto(`/?token=${encodeURIComponent(token)}`, {
++ waitUntil: "domcontentloaded",
++ });
++ await waitForAppShell(page);
++
++ const state = await Promise.race([
++ page
++ .waitForURL(AUTHENTICATED_URL, { timeout: 10_000 })
++ .then(() => "authenticated")
++ .catch(() => undefined),
++ page
++ .locator('input[name="username"]')
++ .waitFor({ state: "visible", timeout: 10_000 })
++ .then(() => "login")
++ .catch(() => undefined),
++ ]);
++
++ if (state === "authenticated") {
++ // The workspace URL can appear before protected bootstrap has mounted
++ // the application. Its pending default-workspace redirect must finish
++ // before the caller navigates to a specific onboarding route.
++ await waitForAuthenticatedAppShell(page);
++ return true;
++ }
++
++ await page
++ .evaluate(() => {
++ window.sessionStorage.removeItem("pulse_auth");
++ })
++ .catch(() => {});
++ return false;
++}
++
async function authenticateWithPrimaryAPIToken(page: Page): Promise<boolean> {
for (const candidate of primaryAPITokenCandidates()) {
// A URL-token navigation reaches an authenticated route before the app's
@@@ -1079,40 -1079,36 +1120,9 @@@
}
rememberPrimaryAPIToken(candidate.token);
-- await page.goto(`/?token=${encodeURIComponent(candidate.token)}`, {
-- waitUntil: "domcontentloaded",
-- });
-- await waitForAppShell(page);
--
-- const state = await Promise.race([
-- page
-- .waitForURL(AUTHENTICATED_URL, { timeout: 10_000 })
-- .then(() => "authenticated")
-- .catch(() => undefined),
-- page
-- .locator('input[name="username"]')
-- .waitFor({ state: "visible", timeout: 10_000 })
-- .then(() => "login")
-- .catch(() => undefined),
-- ]);
--
-- if (state === "authenticated") {
- // The workspace URL can appear before protected bootstrap has mounted
- // the application. Its pending default-workspace redirect must finish
- // before the caller navigates to a specific onboarding route.
- await waitForAuthenticatedAppShell(page);
-- return true;
-- }
--
-- // The probe above already proved this token is valid. A transient app
-- // navigation or websocket delay must not permanently evict it and force
-- // later fixtures through the rate-limited password login path. Only a
-- // definitive 401/403 from the token probe rejects a candidate.
-- await page
-- .evaluate(() => {
-- window.sessionStorage.removeItem("pulse_auth");
-- })
-- .catch(() => {});
++ if (await authenticateWithAPIToken(page, candidate.token)) return true;
++ // A transient navigation or websocket delay cannot evict an admitted
++ // credential. Only a definitive 401/403 from its probe rejects it.
}
return false;