~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
test(ui): fail timed-out checks and exercise CSRF error UX (#7009)
LearningCircuit0618c10b31f4
diff --git a/tests/ui_tests/run_all_tests.js b/tests/ui_tests/run_all_tests.jsindex 7c30c6254e..743a7e716e 100644--- a/tests/ui_tests/run_all_tests.js+++ b/tests/ui_tests/run_all_tests.js@@ -551,8 +551,14 @@ const tests = [},// =====================================================================- // Shard: error-benchmark (5 tests)+ // Shard: error-benchmark (6 tests)// =====================================================================+ {+ name: 'UI Runner Timeout Regression',+ file: 'test_run_all_tests_timeout.test.js',+ shard: 'error-benchmark',+ description: 'A timed-out child fails even when it exits zero on SIGTERM, and is killed if it ignores SIGTERM'+ },{name: 'Error Recovery Test',file: 'test_error_recovery.js',@@ -570,7 +576,8 @@ const tests = [file: 'test_error_and_session_ux_ci.js',shard: 'error-benchmark',description: 'CSRF-rejected mutation shows a visible error toast; unrouted URL renders as an HTML page, not raw JSON; ' +- 'mid-session cookie invalidation on a WRITE is rejected with a visible error and on a GET redirects to login; no uncaught JS errors.'+ 'after mid-session cookie invalidation, a WRITE (401 from the CSRF middleware, no token refresh) and a GET (401) ' ++ 'both redirect to a rendered login form at /auth/login with next=/notes/; no uncaught JS errors.'},{name: 'Benchmark CI Tests',@@ -788,7 +795,7 @@ const tests = [},];-async function runTest(test) {+async function runTest(test, timeoutMs = process.env.CI ? 300000 : 60000) {return new Promise((resolve) => {const startTime = Date.now();console.log(`\n[${ts()}] Running: ${test.name}`);@@ -805,25 +812,31 @@ async function runTest(test) {// with key derivation + 58 tables + 500+ settings, which can take 60-120s.// Subsequent tests may also be slow while the server recovers.// 60 seconds locally for faster feedback.- const isCI = !!process.env.CI;- const timeoutMs = isCI ? 300000 : 60000;+ let timedOut = false;+ let closed = false;+ let forceKillTimeout;const timeout = setTimeout(() => {+ timedOut = true;const elapsed = Math.round((Date.now() - startTime) / 1000);console.log(`\n⏱️ Test timeout: ${test.name} exceeded ${timeoutMs/1000} seconds (${elapsed}s elapsed)`);console.log(`🔪 Sending SIGTERM to PID ${testProcess.pid}...`);testProcess.kill('SIGTERM');- setTimeout(() => {- if (!testProcess.killed) {+ forceKillTimeout = setTimeout(() => {+ if (!closed) {console.log(`🔫 Process still alive, sending SIGKILL to PID ${testProcess.pid}...`);testProcess.kill('SIGKILL');}}, 5000);}, timeoutMs);- testProcess.on('close', (code) => {+ testProcess.on('close', (code, signal) => {+ closed = true;clearTimeout(timeout);+ clearTimeout(forceKillTimeout);const elapsed = Math.round((Date.now() - startTime) / 1000);- const success = code === 0;+ // Puppeteer's SIGTERM handler can close Chrome and let Node exit 0.+ // A killed test never completed its assertions, regardless of code.+ const success = code === 0 && !timedOut;console.log(`[${ts()}] ${success ? '✅' : '❌'} ${test.name}: ${success ? 'PASSED' : 'FAILED'} (${elapsed}s)`);// Grep-friendly line for post-run duration analysis (used to rebalance shards).console.log(`TIMING: ${test.name}: ${elapsed}`);@@ -834,6 +847,8 @@ async function runTest(test) {name: test.name,success,code,+ signal,+ error: timedOut ? `Timed out after ${timeoutMs/1000} seconds` : undefined,duration: elapsed});});@@ -950,7 +965,11 @@ async function runAllTests() {process.exit(failed > 0 ? 1 : 0);}-runAllTests().catch(error => {- console.error('💥 Test runner error:', error);- process.exit(1);-});+if (require.main === module) {+ runAllTests().catch(error => {+ console.error('💥 Test runner error:', error);+ process.exit(1);+ });+}++module.exports = { runTest };diff --git a/tests/ui_tests/test_error_and_session_ux_ci.js b/tests/ui_tests/test_error_and_session_ux_ci.jsindex e286e7d4b9..f6229971f7 100644--- a/tests/ui_tests/test_error_and_session_ux_ci.js+++ b/tests/ui_tests/test_error_and_session_ux_ci.js@@ -41,10 +41,9 @@* the user on a page that looks alive but silently does nothing --* exactly the "silent no-op" risk this task calls out, and exactly* what neither existing test can detect since both drive a fresh- * navigation, not an in-page fetch. (Test 4, a GET, proves this- * works; Test 3, a WRITE, is retargeted onto "rejected + visible- * error shown", not a redirect -- see below and Test 3's own- * comment for why.)+ * navigation, not an in-page fetch. (Test 3 proves this for a WRITE,+ * whose 401 comes from CSRFMiddleware's sign-in check, and Test 4 for+ * a GET, whose 401 comes from `require_auth` -- see below.)* - test_download_and_csrf_flows_ci.js's Tests 1-3 already assert that* CSRF-missing/invalid mutations are rejected with 403 -- but ONLY at* the HTTP-response level (`r.status !== 403` from a raw@@ -55,12 +54,15 @@* every one of those tests. This file's Test 1 drives the exact same* rejection through the real UI (a real button click, not a raw* fetch) and asserts the visible `#notification-banner-assertive`- * toast the user would actually see.+ * toast the user would actually see. The app refreshes a rejected+ * token once and retries, so Test 1 stubs only that refresh, with a+ * token the server rejects again (see Test 1).* - test_settings_save_error_ci.js proves the SAME banner mechanism for* a mocked 5xx on the settings-save endpoint. Not duplicated: this- * file exercises the notes surface with a REAL (not mocked) CSRF- * rejection from the actual middleware, and additionally proves the- * rejected mutation left no trace server-side.+ * file exercises the notes surface with REAL (not mocked) CSRF+ * rejections from the actual middleware, shows the middleware's own+ * message in the banner, and additionally proves the rejected+ * mutation left no trace server-side.** How errors are reported (surveyed, not invented):* static/js/services/ui.js's `showMessage(message, type)` mutates one of@@ -83,8 +85,8 @@* fetch() transparently following a redirect).** ===========================================================================- * ONE MIGRATION REGRESSION FOUND, AND FIXED; ONE PRE-EXISTING BEHAVIOR- * IDENTIFIED AND DELIBERATELY NOT TREATED AS A REGRESSION:+ * ONE MIGRATION REGRESSION FOUND, AND FIXED; ONE DEAD-SESSION BEHAVIOR+ * PINNED:* ===========================================================================** REGRESSION, NOW FIXED -- an unrouted URL used to render as raw JSON,@@ -109,36 +111,24 @@* regression pin: it asserts `content-type: text/html` on a plain* top-level navigation to an unrouted URL.*- * PRE-EXISTING, NOT A REGRESSION -- after a session cookie is fully- * cleared from the browser, a WRITE action (not a GET) does not redirect;- * it surfaces a raw, developer-facing "CSRF token missing: fetch- * /auth/csrf-token first" toast instead, because CSRFMiddleware- * (web/dependencies/csrf.py) reads its token from that SAME now-empty- * session and rejects with 403 BEFORE `Depends(require_auth)` ever runs --- * the 401-driven client-side redirect in- * safeFetchWithAuth/fetchWithErrorHandling only special-cases status 401,- * so this 403 sails past it (Test 4, a GET on the identical dead session,- * proves the 401 path itself is fine -- this is specifically a WRITE +- * dead-session interaction). Checked against pre-migration `main` and- * found to behave the same way there, so this is NOT something the- * migration broke: Flask-WTF's `CSRFProtect` registers a `before_request`- * hook, which runs before `@login_required` for the identical reason, and- * `main`'s own `@app.errorhandler(CSRFError)` (`web/app_factory.py:1053-1057`)- * returned `make_response(jsonify({"error": str(error.description)}), 400)`- * -- also a raw, developer-facing message, also not a login redirect. Both- * branches show a raw error instead of redirecting, so this is a- * pre-existing UX wart that predates this PR and is out of scope for it.- * Test 3 below is retargeted onto the invariant that genuinely holds- * today -- the write must be REJECTED (never silently succeed against a- * dead session) and the user must see a VISIBLE error (never a silent- * no-op) -- rather than onto the specific raw error shown, or onto a- * redirect. See Test 3's own comment for the fuller record, including the- * follow-up this leaves on the table.+ * DEAD-SESSION WRITES REDIRECT TO LOGIN, LIKE GETS -- once the session+ * cookie is cleared from the browser, a WRITE from an already-rendered+ * page is rejected with 401 and the app sends the user to login.+ * services/api.js's `fetchWithCsrfRecovery()` adds the page's+ * X-LDR-Auth-Context header to eligible same-origin writes, and+ * CSRFMiddleware (web/dependencies/csrf.py) checks that header BEFORE the+ * session's CSRF token. With no session, `get_auth_context()` finds no+ * login, so the middleware answers 401 {"error": "Authentication+ * required"} before any handler runs, and safeFetchWithAuth turns that+ * into the same client-side redirect a dead-session GET gets (Test 4).+ * A write sent without the context header (a FormData upload, for+ * example) still gets the middleware's 403 "CSRF token missing: fetch+ * /auth/csrf-token first" instead. Test 3 below is the pin.** Screenshots: opt-in only via tests/ui_tests/screenshot_helper.js (no-op* unless LDR_UI_SCREENSHOTS is set -- see that file's header). Captured on- * the visible error banner, on the 404 response, and on any assertion- * failure.+ * the visible error banner, on the 404 response, on both login redirects,+ * and on any assertion failure.** Registered in the `error-benchmark` shard (tests/ui_tests/run_all_tests.js)* -- same theme as test_error_handling_ci.js / test_error_recovery.js.@@ -188,6 +178,40 @@ async function waitForBannerText(page, timeout) {return page.$eval(`${ERROR_BANNER_SELECTOR} span`, (el) => el.textContent.trim());}+/** Keep response-body reads from hanging the entire shard without a diagnosis. */+async function withTimeout(promise, timeout, label) {+ let timer;+ try {+ return await Promise.race([+ promise,+ new Promise((_, reject) => {+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeout}ms`)), timeout);+ }),+ ]);+ } finally {+ clearTimeout(timer);+ }+}++/**+ * page.waitForResponse(), limited to main-frame requests that start after+ * this call. A URL does not say which page sent a request, so without this+ * a response to an earlier request (one the previous page sent, or one+ * already in flight) could satisfy the wait. Puppeteer emits a request's+ * 'request' event before its 'response' event, so a response's request is+ * already recorded when the predicate sees it.+ */+function waitForResponseToNewRequest(page, predicate, options) {+ const newRequests = new WeakSet();+ const recordRequest = (request) => {+ if (request.frame() === page.mainFrame()) newRequests.add(request);+ };+ page.on('request', recordRequest);+ return page+ .waitForResponse((response) => newRequests.has(response.request()) && predicate(response), options)+ .finally(() => page.off('request', recordRequest));+}+/*** Track same-origin requests until their response headers arrive (or the* request fails). Set-Cookie is applied at the header boundary, so a short@@ -274,6 +298,116 @@ function trackSameOriginResponseHeaders(page, origin) {};}+/**+ * Render /notes/ while signed in, let its bootstrap traffic settle, then+ * delete the browser's session cookie. The page keeps the signed-in user's+ * CSRF token and auth context, but the next request carries no session.+ * Throws a "FAILED SETUP" error if that state cannot be reached.+ *+ * The setup starts from about:blank, which sends no requests. The page that+ * was open before can still have requests in flight: the post-login home+ * page, for one, extends base.html, whose theme.js requests+ * /settings/api/app.theme, one of the three bootstrap paths below. Each+ * bootstrap wait also accepts only a request that starts after the wait is+ * set up, so a late response to an earlier page's request is never taken+ * for this page's own.+ *+ * A rendered button does not prove that the page's authenticated bootstrap+ * responses have finished. SessionMiddleware can emit Set-Cookie on any of+ * them; deleting the cookie while one is in flight lets that old response+ * recreate it. The header tracker stays active through deletion, and the+ * idle timer resets whenever another same-origin request starts. The three+ * named API checks also prove initialization worked. They check the status+ * only: Set-Cookie arrives with the headers, so no response body is read.+ */+async function openNotesWithDeadSession(page) {+ await page.goto('about:blank', { waitUntil: 'load', timeout: TIMEOUTS.navigation });++ const responseHeaderTracker = trackSameOriginResponseHeaders(page, new URL(BASE_URL).origin);+ try {+ const waitForBootstrapGet = (pathname) => waitForResponseToNewRequest(+ page,+ (response) => response.request().method() === 'GET' && new URL(response.url()).pathname === pathname,+ { timeout: TIMEOUTS.navigation }+ );+ const [notesBootstrapResponse, collectionsBootstrapResponse, themeBootstrapResponse] = await Promise.all([+ waitForBootstrapGet('/notes/api/notes'),+ waitForBootstrapGet('/library/api/collections'),+ waitForBootstrapGet('/settings/api/app.theme'),+ page.goto(`${BASE_URL}/notes/`, {+ waitUntil: 'load',+ timeout: TIMEOUTS.navigation,+ }),+ ]);+ await page.waitForSelector('[data-action="create-new-note"]', { timeout: TIMEOUTS.selector });++ for (const response of [notesBootstrapResponse, collectionsBootstrapResponse, themeBootstrapResponse]) {+ if (response.status() !== 200) {+ throw new Error(+ `FAILED SETUP: ${new URL(response.url()).pathname} bootstrap returned HTTP ${response.status()}`+ );+ }+ }+ await responseHeaderTracker.waitForIdle(RESPONSE_HEADER_IDLE_MS, TIMEOUTS.navigation);++ const cookiesBeforeExpiry = await page.cookies();+ const sessionCookieToKill = cookiesBeforeExpiry.find((cookie) => cookie.name === 'session');+ if (!sessionCookieToKill) {+ throw new Error('FAILED SETUP: no "session" cookie found before invalidating it');+ }+ await page.deleteCookie({+ name: 'session',+ domain: sessionCookieToKill.domain,+ path: sessionCookieToKill.path,+ });++ // If a response crossed the first delete boundary, wait until header+ // activity is quiet again and clear only the session cookie it may+ // have recreated.+ await responseHeaderTracker.waitForIdle(RESPONSE_HEADER_IDLE_MS, TIMEOUTS.navigation);+ const cookiesAfterHeaderIdle = await page.cookies();+ for (const cookie of cookiesAfterHeaderIdle.filter((item) => item.name === 'session')) {+ await page.deleteCookie({ name: cookie.name, domain: cookie.domain, path: cookie.path });+ }++ const cookiesAfterExpiry = await page.cookies();+ if (cookiesAfterExpiry.some((cookie) => cookie.name === 'session')) {+ throw new Error('FAILED SETUP: session cookie still present after bootstrap settled');+ }+ } finally {+ responseHeaderTracker.dispose();+ }+}++/**+ * Assert that an in-page action on a dead session landed on a real login+ * form with next=/notes/, not a broken page or a raw JSON body.+ */+async function assertLoginPageRendered(page, action) {+ const finalUrl = new URL(page.url());+ if (finalUrl.pathname !== '/auth/login') {+ throw new Error(+ `GENUINE DEFECT: after a mid-session cookie invalidation, an in-page ${action} action ` ++ `did not send the user to login. Landed on: ${page.url()}`+ );+ }+ const nextParam = finalUrl.searchParams.get('next');+ if (nextParam !== '/notes/') {+ throw new Error(`Expected next=/notes/ so the user lands back where they were, got next=${nextParam}`);+ }++ await page.waitForSelector('input[name="username"]', { timeout: TIMEOUTS.selector });+ const hasPasswordField = await page.$('input[name="password"]');+ const hasSubmitButton = await page.$('button[type="submit"]');+ const contentType = (await page.evaluate(() => document.contentType)) || '';+ if (!hasPasswordField || !hasSubmitButton) {+ throw new Error('GENUINE DEFECT: landed on /auth/login but it is missing a functional login form (username/password/submit)');+ }+ if (!contentType.startsWith('text/html')) {+ throw new Error(`GENUINE DEFECT: /auth/login rendered as "${contentType}", not an HTML page`);+ }+}+async function run() {console.log(`Running error / browser-session-loss UX tests (CI mode: ${isCI})`);console.log(`Screenshots: ${screenshotsEnabled() ? 'ENABLED (LDR_UI_SCREENSHOTS set)' : 'disabled (default)'}`);@@ -286,8 +420,8 @@ async function run() {page.setDefaultNavigationTimeout(60000);}- // Aggregate JS-error tracking across the WHOLE run (Tests 1-3) -- this- // is what Test 4 asserts on. Attached once, here, rather than per-test,+ // Aggregate JS-error tracking across the WHOLE run (Tests 1-4) -- this+ // is what Test 5 asserts on. Attached once, here, rather than per-test,// so nothing that happens between tests is missed.const allConsoleErrors = [];const allPageErrors = [];@@ -334,6 +468,35 @@ async function run() {await page.type('#note-title', shouldNotExistTitle);await page.type('#note-content', 'This save must be rejected by a tampered CSRF token.');+ // The app recovers a stale token once: on the middleware's marked+ // 403 it fetches /auth/csrf-token and retries with the token it+ // gets back. Stub only that refresh, with the endpoint's success+ // shape (200, a csrf_token, and this page's own auth_context) but+ // a token the server never issued. The one permitted retry then+ // reaches the real CSRF middleware and is rejected again. The+ // endpoint answers only 200, 401 or 409: a 200 whose token is+ // rejected again is how a write ends in a CSRF failure on this+ // page, while a 401 redirects to login and a 409 reports a changed+ // sign-in. The stub carries no message, so the banner can only+ // show the server's. Navigation in Test 2 restores fetch.+ const tamperedToken = 'tampered-invalid-csrf-token';+ const refreshedToken = 'refreshed-but-still-invalid-csrf-token';+ await page.evaluate((token) => {+ const realFetch = window.fetch.bind(window);+ window.fetch = (input, options) => {+ const url = typeof input === 'string' ? input : input?.url;+ if (url && new URL(url, window.location.href).pathname === '/auth/csrf-token') {+ window.__csrfRefreshAttempts = (window.__csrfRefreshAttempts || 0) + 1;+ const authContext = new window.Headers(options?.headers).get('X-LDR-Auth-Context');+ return Promise.resolve(new Response(+ JSON.stringify({ csrf_token: token, auth_context: authContext }),+ { status: 200, headers: { 'Content-Type': 'application/json' } }+ ));+ }+ return realFetch(input, options);+ };+ }, refreshedToken);+// Tamper the CSRF token IN THE DOM only -- this mutates the// live <meta> the page's own JS reads (getCsrfToken() / both// notes.js's and note-detail.js's getCSRFToken() delegate to@@ -342,30 +505,61 @@ async function run() {// later page.goto() elsewhere in this file gets a fresh,// VALID token rendered straight from the server template --// no restore step is needed.- await page.evaluate(() => {+ await page.evaluate((token) => {const meta = document.querySelector('meta[name="csrf-token"]');- if (meta) meta.setAttribute('content', 'tampered-invalid-csrf-token');- });-- const isCreateNotePost = (r) =>- r.url().endsWith('/notes/api/notes') && r.request().method() === 'POST';- const postRespPromise = page.waitForResponse(isCreateNotePost, { timeout: TIMEOUTS.navigation });+ if (meta) meta.setAttribute('content', token);+ }, tamperedToken);++ // Tell the two attempts apart by the token each one sent.+ const isCreateNotePostWithToken = (token) => (r) =>+ new URL(r.url()).pathname === '/notes/api/notes'+ && r.request().method() === 'POST'+ && r.request().headers()['x-csrftoken'] === token;+ const firstRespPromise = page.waitForResponse(+ isCreateNotePostWithToken(tamperedToken), { timeout: TIMEOUTS.navigation }+ );+ const retryRespPromise = page.waitForResponse(+ isCreateNotePostWithToken(refreshedToken), { timeout: TIMEOUTS.navigation }+ );await page.click('#save-note-btn');- const postResp = await postRespPromise;- const postBody = await postResp.json().catch(() => null);- if (postResp.status() !== 403) {- throw new Error(`Expected the real CSRF middleware to reject with 403, got status=${postResp.status()} body=${JSON.stringify(postBody)}`);- }- if (!postBody || !/csrf/i.test(postBody.error || '')) {- throw new Error(`Expected a CSRF-flavored error body, got: ${JSON.stringify(postBody)}`);+ const [firstResp, retryResp] = await Promise.all([firstRespPromise, retryRespPromise]).catch((e) => {+ throw new Error(`Expected the original create and one retry with the refreshed token: ${e.message}`);+ });+ // Check status and headers only. fetchWithCsrfRecovery() never+ // reads the original 403's body, and Chrome does not finish+ // loading a no-store fetch body until the page reads it, so a+ // Puppeteer body read of that response would never settle.+ for (const [label, resp] of [['original', firstResp], ['retried', retryResp]]) {+ const marker = resp.headers()['x-ldr-csrf-rejected'];+ if (resp.status() !== 403 || marker !== '1') {+ throw new Error(+ `Expected the real CSRF middleware to reject the ${label} create with a marked 403, ` ++ `got status=${resp.status()} x-ldr-csrf-rejected=${marker}`+ );+ }}// The visible signal a real user would see.const bannerText = await waitForBannerText(page, TIMEOUTS.selector);await capture(page, SCREENSHOT_PREFIX, 'csrf_error_banner');- if (!/csrf/i.test(bannerText)) {- throw new Error(`GENUINE DEFECT: notification banner did not surface a CSRF-related message -- got: "${bannerText}"`);+ // saveNote() read the retry's body before showing the banner, so+ // this read can settle; it is bounded anyway.+ const retryBody = await withTimeout(+ retryResp.json().catch(() => null), TIMEOUTS.selector, 'CSRF retry rejection body'+ );+ if (!retryBody || !/csrf/i.test(retryBody.error || '')) {+ throw new Error(`Expected a CSRF-flavored error body on the retried create, got: ${JSON.stringify(retryBody)}`);+ }+ const refreshAttempts = await page.evaluate(() => window.__csrfRefreshAttempts || 0);+ if (refreshAttempts !== 1) {+ throw new Error(`Expected one CSRF refresh attempt, got ${refreshAttempts}`);+ }+ if (bannerText !== retryBody.error) {+ throw new Error(+ `GENUINE DEFECT: notification banner did not show the server's CSRF rejection ` ++ `("${retryBody.error}") -- got: "${bannerText}"`+ );}// Not a silent no-op: the modal is still open with the user's@@ -380,16 +574,16 @@ async function run() {}// Nothing was actually created server-side.- const apiCheck = await page.evaluate(async (title) => {+ const apiCheck = await withTimeout(page.evaluate(async (title) => {const r = await fetch(`/notes/api/notes?search=${encodeURIComponent(title)}`, { credentials: 'same-origin' });const body = await r.json().catch(() => null);return { status: r.status, count: (body?.notes || []).length };- }, shouldNotExistTitle);+ }, shouldNotExistTitle), TIMEOUTS.selector, 'note absence check');if (apiCheck.status !== 200 || apiCheck.count !== 0) {- throw new Error(`GENUINE DEFECT: a note titled "${shouldNotExistTitle}" exists despite the rejected (403) create request: ${JSON.stringify(apiCheck)}`);+ throw new Error(`GENUINE DEFECT: a note titled "${shouldNotExistTitle}" exists despite the rejected (403) create requests: ${JSON.stringify(apiCheck)}`);}- console.log(`PASSED (403 rejected, banner="${bannerText}", modal stayed open, nothing was created)`);+ console.log(`PASSED (original and retried creates rejected with 403, banner="${bannerText}", modal stayed open, nothing was created)`);passed++;} catch (e) {console.log(`FAILED: ${e.message}`);@@ -450,302 +644,172 @@ async function run() {}// ---------------------------------------------------------------- // Tests 3 + 4 share one dead-session setup (navigate to /notes/,- // settle its bootstrap traffic, then clear the session cookie).- // Order is deliberate: Test 3 (a WRITE) is expected to leave the page ON- // /notes/ (see its own comment for why), so it must run BEFORE- // Test 4 (a GET, which DOES redirect to /auth/login) -- once a- // redirect happens there is no way back to an authenticated-- // feeling /notes/ page (a fresh page.goto('/notes/') with the- // cookie already gone would just hit the server-side HTML-route- // 302 before any app JS ran, which is the already-covered- // full-navigation case from test_error_handling_ci.js /- // test_download_and_csrf_flows_ci.js -- see file header).- //- // The scenario for both: a page is already loaded and the user is- // mid-session when the browser loses its session cookie (for- // example, an explicitly cleared cookie jar). The signed cookie- // carries the browser's username and CSRF claims, so once it is gone- // the next request has neither even though the app also validates a+ // Tests 3 + 4: a page is already loaded and the user is mid-session+ // when the browser loses its session cookie (for example, an+ // explicitly cleared cookie jar). The signed cookie carries the+ // browser's username and CSRF claims, so once it is gone the next+ // request has neither even though the app also validates a// server-side session id. Their next authenticated ACTION -- not a- // fresh page load -- must be handled gracefully by the app's own- // JS (safeFetchWithAuth), not leave them looking at a page that+ // fresh page load -- must be handled gracefully by the app's own JS+ // (safeFetchWithAuth), not leave them looking at a page that// silently does nothing.+ //+ // Both actions end on /auth/login, so each test starts from its own+ // signed-in /notes/ page and then deletes its cookie+ // (openNotesWithDeadSession). Loading /notes/ AFTER the cookie is+ // gone would instead hit the server-side HTML-route 302 before any+ // app JS ran, which is the already-covered full-navigation case+ // from test_error_handling_ci.js / test_download_and_csrf_flows_ci.js+ // (see file header).// ---------------------------------------------------------------- // A rendered button does not prove that the page's authenticated- // bootstrap responses have finished. SessionMiddleware can emit- // Set-Cookie on any of them; deleting the cookie while one is in- // flight lets that old response recreate it. The header tracker stays- // active through deletion, and the idle timer resets whenever another- // same-origin request starts. The three named API checks also prove- // initialization worked.- let sessionCookieInvalidated = false;- const responseHeaderTracker = trackSameOriginResponseHeaders(page, new URL(BASE_URL).origin);- try {- const isBootstrapGet = (response, pathname) =>- response.request().method() === 'GET' && new URL(response.url()).pathname === pathname;- const [notesBootstrapResponse, collectionsBootstrapResponse, themeBootstrapResponse] = await Promise.all([- page.waitForResponse(- (response) => isBootstrapGet(response, '/notes/api/notes'),- { timeout: TIMEOUTS.navigation }- ),- page.waitForResponse(- (response) => isBootstrapGet(response, '/library/api/collections'),- { timeout: TIMEOUTS.navigation }- ),- page.waitForResponse(- (response) => isBootstrapGet(response, '/settings/api/app.theme'),- { timeout: TIMEOUTS.navigation }- ),- page.goto(`${BASE_URL}/notes/`, {- waitUntil: 'load',- timeout: TIMEOUTS.navigation,- }),- ]);- await page.waitForSelector('[data-action="create-new-note"]', { timeout: TIMEOUTS.selector });- const bootstrapResponses = [- notesBootstrapResponse,- collectionsBootstrapResponse,- themeBootstrapResponse,- ];- for (const response of bootstrapResponses) {- if (response.status() !== 200) {+ // ---------------------------------------------------------------+ // Test 3: dead session + a WRITE (mutation) is rejected with 401,+ // and the app sends the user to login.+ //+ // Why a 401 and not a CSRF 403: fetchWithCsrfRecovery() in+ // services/api.js adds the page's X-LDR-Auth-Context header to this+ // same-origin JSON POST, and CSRFMiddleware+ // (web/dependencies/csrf.py) checks that header before the session's+ // CSRF token. The session is empty, so get_auth_context() returns+ // None and the middleware answers 401 {"error": "Authentication+ // required"} before any handler runs. That response carries no+ // X-LDR-CSRF-Rejected marker, so the app neither refreshes the token+ // nor retries; safeFetchWithAuth() calls redirectToLogin(), the same+ // path the GET in Test 4 takes.+ // ---------------------------------------------------------------+ console.log('Test 3: dead session + a WRITE action -- 401, then a client-side redirect to login (not a silent no-op)');+ try {+ await openNotesWithDeadSession(page);+ await page.click('[data-action="create-new-note"]');+ await page.waitForSelector('#note-title', { visible: true, timeout: TIMEOUTS.selector });+ await page.type('#note-title', `ldr-ui-session-expiry-write-${uniqueSuffix}`);+ await page.type('#note-content', 'This create must never reach the server as a success -- session is dead.');++ const pageAuthContext = await page+ .$eval('meta[name="auth-context"]', (el) => el.getAttribute('content'))+ .catch(() => null);+ let csrfRefreshRequests = 0;+ const countCsrfRefresh = (request) => {+ if (new URL(request.url()).pathname === '/auth/csrf-token') csrfRefreshRequests++;+ };+ page.on('request', countCsrfRefresh);+ try {+ const isCreateNotePost = (r) =>+ new URL(r.url()).pathname === '/notes/api/notes' && r.request().method() === 'POST';+ const postRespPromise = waitForResponseToNewRequest(+ page, isCreateNotePost, { timeout: TIMEOUTS.navigation }+ );+ const navPromise = page+ .waitForNavigation({ waitUntil: 'domcontentloaded', timeout: TIMEOUTS.navigation })+ .catch(() => null);+ await page.click('#save-note-btn');++ const postResp = await postRespPromise;+ const status = postResp.status();+ const sentContext = postResp.request().headers()['x-ldr-auth-context'];+ const marker = postResp.headers()['x-ldr-csrf-rejected'];+ console.log(` (observed: status=${status} x-ldr-csrf-rejected=${marker})`);+ if (status !== 401) {+ // Read the body only to explain a failure, and bound the+ // read: Chrome does not finish loading a no-store fetch+ // body that the page never reads (see Test 1).+ const body = await withTimeout(postResp.text(), TIMEOUTS.selector, 'dead-session write body')+ .catch((err) => `<unavailable: ${err.message}>`);throw new Error(- `FAILED SETUP: ${new URL(response.url()).pathname} bootstrap returned HTTP ${response.status()}`+ `GENUINE DEFECT: expected CSRFMiddleware to reject a dead-session write with 401, ` ++ `got HTTP ${status} (body: ${body})`);}- }- await Promise.all(bootstrapResponses.map((response) => response.text()));- await responseHeaderTracker.waitForIdle(RESPONSE_HEADER_IDLE_MS, TIMEOUTS.navigation);-- const cookiesBeforeExpiry = await page.cookies();- const sessionCookieToKill = cookiesBeforeExpiry.find((cookie) => cookie.name === 'session');- if (!sessionCookieToKill) {- console.log('Tests 3+4: FAILED SETUP: no "session" cookie found before invalidating it');- failed += 2;- } else {- await page.deleteCookie({- name: 'session',- domain: sessionCookieToKill.domain,- path: sessionCookieToKill.path,- });-- // If a response crossed the first delete boundary, wait until- // header activity is quiet again and clear only the session- // cookie it may have recreated. This preserves every test and- // establishes the dead-session precondition before Test 3.- await responseHeaderTracker.waitForIdle(RESPONSE_HEADER_IDLE_MS, TIMEOUTS.navigation);- const cookiesAfterHeaderIdle = await page.cookies();- for (const cookie of cookiesAfterHeaderIdle.filter((item) => item.name === 'session')) {- await page.deleteCookie({ name: cookie.name, domain: cookie.domain, path: cookie.path });+ if (!pageAuthContext || sentContext !== pageAuthContext) {+ throw new Error(+ `Expected the write to carry this page's X-LDR-Auth-Context (${pageAuthContext}), got ${sentContext}`+ );+ }+ if (marker !== undefined) {+ throw new Error(`A dead-session write was answered as a CSRF rejection (x-ldr-csrf-rejected=${marker})`);}- const cookiesAfterExpiry = await page.cookies();- if (cookiesAfterExpiry.some((cookie) => cookie.name === 'session')) {- console.log('Tests 3+4: FAILED SETUP: session cookie still present after bootstrap settled');- failed += 2;- } else {- sessionCookieInvalidated = true;+ // The app's own JS must navigate to login itself; a broken+ // version would leave the page sitting there with no reaction.+ await navPromise;+ await assertLoginPageRendered(page, 'WRITE');+ if (csrfRefreshRequests !== 0) {+ throw new Error(`Expected no CSRF token refresh for a signed-out write, saw ${csrfRefreshRequests}`);}+ await capture(page, SCREENSHOT_PREFIX, 'session_expiry_write_redirected_to_login');++ console.log(`PASSED (401 on the write, client-side redirect to ${page.url()}, real login form rendered)`);+ passed++;+ } finally {+ page.off('request', countCsrfRefresh);}- } finally {- responseHeaderTracker.dispose();+ } catch (e) {+ console.log(`FAILED: ${e.message}`);+ await captureOnFailure(page, SCREENSHOT_PREFIX, 'session_expiry_write', false);+ failed++;}- if (sessionCookieInvalidated) {- // ------------------------------------------------------------ // Test 3: dead session + a WRITE (mutation) action is- // REJECTED (never silently succeeds) and shows a VISIBLE- // error (never a silent no-op).- //- // This does NOT assert a redirect to /auth/login. Root- // cause of why there isn't one: CSRFMiddleware- // (web/dependencies/csrf.py) runs BEFORE the route's- // `Depends(require_auth)` and reads its token straight out- // of `request.session["_csrf_token"]`. The username and- // CSRF claims live in the signed cookie, while authentication- // also validates its `session_id` against the server-side- // session manager. Removing the browser cookie therefore- // removes both claims from the next request. So the very next- // WRITE action (not a GET, see Test 4) hits- // CSRFMiddleware's `if not session_token: return 403- // {"error": "CSRF token missing: fetch /auth/csrf-token- // first"}` BEFORE `require_auth` ever runs -- the request- // never reaches the 401 path Test 4 exercises, and- // notes.js's `saveNote()` surfaces that raw, developer-- // facing 403 message via the same notification banner- // instead of redirecting to login. `shouldRedirectToLoginOn401()`- // in api.js only special-cases status 401, so this 403- // sails right past it.- //- // PRE-EXISTING, NOT A MIGRATION REGRESSION (see file- // header for the full record): checked against- // pre-migration `main` and found to behave the same way.- // Flask-WTF's `CSRFProtect` also registers a- // `before_request` hook that runs before `@login_required`- // for the identical reason, and `main`'s own- // `@app.errorhandler(CSRFError)`- // (`web/app_factory.py:1053-1057`) returned- // `make_response(jsonify({"error": str(error.description)}), 400)`- // -- also a raw, developer-facing message, also not a login- // redirect. So this is retargeted onto the invariant that- // actually matters and is actually true today (rejected +- // visible error), not weakened to paper over a defect --- // the previously-asserted "redirects to login" behavior was- // never correct-by-parity with `main` to begin with.- //- // KNOWN FOLLOW-UP (out of scope here, predates this PR):- // ideally a dead-session WRITE would redirect to login the- // same way a dead-session GET does (Test 4) instead of- // showing a raw CSRF error. Worth fixing someday by having- // CSRFMiddleware distinguish "no session at all" from- // "session exists but token missing/wrong" and defer the- // former to `require_auth`, or by having the client- // recognize this specific 403 shape and redirect anyway.- // ------------------------------------------------------------ console.log('Test 3: dead session + a WRITE action -- mutation rejected, visible error shown (not a silent no-op)');- try {- await page.click('[data-action="create-new-note"]');- await page.waitForSelector('#note-title', { visible: true, timeout: TIMEOUTS.selector });- await page.type('#note-title', `ldr-ui-session-expiry-write-${uniqueSuffix}`);- await page.type('#note-content', 'This create must never reach the server as a success -- session is dead.');-- const bannerTextBeforeWrite = await page- .$eval(`${ERROR_BANNER_SELECTOR} span`, (el) => el.textContent.trim())- .catch(() => '');- if (bannerTextBeforeWrite) {- throw new Error(- `FAILED SETUP: assertive banner already contained text before the write: "${bannerTextBeforeWrite}"`- );- }-- const isCreateNotePost = (r) =>- r.url().endsWith('/notes/api/notes') && r.request().method() === 'POST';- const postRespPromise = page.waitForResponse(isCreateNotePost, { timeout: TIMEOUTS.navigation });- await page.click('#save-note-btn');-- const postResp = await postRespPromise;- const postBody = await postResp.json().catch(() => null);- console.log(` (observed: status=${postResp.status()} body=${JSON.stringify(postBody)})`);-- // (a) rejected -- must not silently succeed against a- // dead session.- if (postResp.status() < 400 || postResp.status() >= 500) {- throw new Error(- `GENUINE DEFECT: expected a client-error (4xx) rejection of a dead-session write, ` +- `got HTTP ${postResp.status()} (body: ${JSON.stringify(postBody)})`- );- }+ // ---------------------------------------------------------------+ // Test 4: a dead session + a READ (GET) action -- isolates the auth+ // (401) code path from the CSRF layer above it (a GET carries no+ // CSRF token requirement; CSRFMiddleware only gates+ // POST/PUT/PATCH/DELETE). Uses the notes search box, typing 1+ // character -- below SemanticSearch.MIN_QUERY_LENGTH=2, so+ // loadNotes() always takes the plain keyword-listing GET path+ // regardless of AI search mode (see notes.js's `hasQuery` check),+ // avoiding any LLM/embeddings dependency.+ // ---------------------------------------------------------------+ console.log('Test 4: dead session + a GET action -- redirects to login (not a broken page/raw JSON/silent no-op)');+ try {+ // Test 3 leaves this browser on /auth/login without a session.+ // Load the login page first, so the sign-in check cannot mistake+ // a leftover /notes/ page for a live session, then sign in again.+ await page.goto(`${BASE_URL}/auth/login`, {+ waitUntil: 'domcontentloaded',+ timeout: TIMEOUTS.navigation,+ });+ await auth.ensureAuthenticatedWithTimeout();+ await openNotesWithDeadSession(page);++ await page.waitForSelector('#ldr-notes-search', { timeout: TIMEOUTS.selector });+ // The page's own bootstrap listing (/notes/api/notes?limit=...)+ // has the same path, so match the typed query too.+ const searchTerm = 'a';+ const isNotesSearchGet = (r) => {+ const url = new URL(r.url());+ return url.pathname === '/notes/api/notes'+ && url.searchParams.get('search') === searchTerm+ && r.request().method() === 'GET';+ };+ const getRespPromise = waitForResponseToNewRequest(+ page, isNotesSearchGet, { timeout: TIMEOUTS.navigation }+ );+ const navPromise = page+ .waitForNavigation({ waitUntil: 'domcontentloaded', timeout: TIMEOUTS.navigation })+ .catch(() => null);+ await page.type('#ldr-notes-search', searchTerm);++ const getResp = await getRespPromise;+ if (getResp.status() !== 401) {+ throw new Error(`Expected the invalidated session to 401 the notes-list GET, got ${getResp.status()}`);+ }- // (b) visible -- the user must see SOMETHING, not a- // page that quietly did nothing. waitForBannerText()- // itself times out (failing this test) if the banner- // never gets non-empty text.- const bannerText = await waitForBannerText(page, TIMEOUTS.selector);-- console.log(`PASSED (write rejected with HTTP ${postResp.status()}, banner shows: "${bannerText}")`);- passed++;- } catch (e) {- console.log(`FAILED: ${e.message}`);- await captureOnFailure(page, SCREENSHOT_PREFIX, 'session_expiry_write', false);- failed++;- } finally {- // Leave a clean page for Test 4 regardless of outcome:- // the create-note modal is still open (the rejected- // write never navigates away) -- dismiss it via a real- // Cancel click (no auth/network involved) so Test 4's- // search-box interaction below isn't blocked by the- // modal overlay. If this ever starts redirecting- // instead (see the "known follow-up" note above), we'd- // already be on /auth/login and this is a harmless- // no-op.- await page- .click('#noteModal button[data-bs-dismiss="modal"]')- .catch(() => {});- }+ // The app's own JS (safeFetchWithAuth) must notice the 401 and+ // navigate to login itself -- this await is what proves it's not+ // a silent no-op (a broken version would just leave the page+ // sitting there forever with no visible reaction).+ await navPromise;+ await assertLoginPageRendered(page, 'GET');+ await capture(page, SCREENSHOT_PREFIX, 'session_expiry_redirected_to_login');- // ------------------------------------------------------------ // Test 4: the SAME dead session, but via a READ (GET)- // action -- isolates the auth (401) code path from the CSRF- // layer above it (a GET carries no CSRF token requirement;- // CSRFMiddleware only gates POST/PUT/PATCH/DELETE). Uses the- // notes search box, typing 1 character -- below- // SemanticSearch.MIN_QUERY_LENGTH=2, so loadNotes() always- // takes the plain keyword-listing GET path regardless of AI- // search mode (see notes.js's `hasQuery` check), avoiding- // any LLM/embeddings dependency.- // ------------------------------------------------------------ console.log('Test 4: dead session + a GET action -- redirects to login (not a broken page/raw JSON/silent no-op)');- try {- if (!page.url().includes('/notes/')) {- // Test 3 unexpectedly already redirected us (the- // pre-existing "WRITE shows a raw CSRF error instead- // of redirecting" behavior described in Test 3's- // comment no longer applies) -- a fresh load of- // /notes/ now would just re-hit the same already-- // proven server-side redirect (session is still- // dead), not the in-page GET path this test targets.- // Nothing further to prove here.- console.log(` (already on ${page.url()} from Test 3 -- GET-triggered redirect not separately exercisable; Test 3 apparently redirected on its own this run)`);- console.log('PASSED (vacuously -- session is already confirmed dead and login already reached)');- passed++;- } else {- await page.waitForSelector('#ldr-notes-search', { timeout: TIMEOUTS.selector });- const isNotesListGet = (r) =>- r.url().includes('/notes/api/notes?') && r.request().method() === 'GET';- const getRespPromise = page.waitForResponse(isNotesListGet, { timeout: TIMEOUTS.navigation });- const navPromise = page- .waitForNavigation({ waitUntil: 'domcontentloaded', timeout: TIMEOUTS.navigation })- .catch(() => null);- await page.type('#ldr-notes-search', 'a');-- const getResp = await getRespPromise;- if (getResp.status() !== 401) {- throw new Error(`Expected the invalidated session to 401 the notes-list GET, got ${getResp.status()}`);- }-- // The app's own JS (safeFetchWithAuth) must notice- // the 401 and navigate to login itself -- this await- // is what proves it's not a silent no-op (a broken- // version would just leave the page sitting there- // forever with no visible reaction).- await navPromise;- const finalUrl = new URL(page.url());- if (finalUrl.pathname !== '/auth/login') {- throw new Error(- `GENUINE DEFECT: after a mid-session cookie invalidation, an in-page GET action ` +- `did not send the user to login. Landed on: ${page.url()}`- );- }- const nextParam = finalUrl.searchParams.get('next');- if (nextParam !== '/notes/') {- throw new Error(`Expected next=/notes/ so the user lands back where they were, got next=${nextParam}`);- }-- // Not a broken page or raw JSON blob: a real,- // functional login form is rendered.- await page.waitForSelector('input[name="username"]', { timeout: TIMEOUTS.selector });- const hasPasswordField = await page.$('input[name="password"]');- const hasSubmitButton = await page.$('button[type="submit"]');- const contentType = (await page.evaluate(() => document.contentType)) || '';- if (!hasPasswordField || !hasSubmitButton) {- throw new Error('GENUINE DEFECT: landed on /auth/login but it is missing a functional login form (username/password/submit)');- }- if (!contentType.startsWith('text/html')) {- throw new Error(`GENUINE DEFECT: /auth/login rendered as "${contentType}", not an HTML page`);- }- await capture(page, SCREENSHOT_PREFIX, 'session_expiry_redirected_to_login');-- console.log(`PASSED (401 on the GET, client-side redirect to ${page.url()}, real login form rendered)`);- passed++;- }- } catch (e) {- console.log(`FAILED: ${e.message}`);- await captureOnFailure(page, SCREENSHOT_PREFIX, 'session_expiry_get', false);- failed++;- }- }+ console.log(`PASSED (401 on the GET, client-side redirect to ${page.url()}, real login form rendered)`);+ passed++;+ } catch (e) {+ console.log(`FAILED: ${e.message}`);+ await captureOnFailure(page, SCREENSHOT_PREFIX, 'session_expiry_get', false);+ failed++;+ }// ---------------------------------------------------------------// Test 5: no uncaught JS errors were observed during any of thediff --git a/tests/ui_tests/test_run_all_tests_timeout.test.js b/tests/ui_tests/test_run_all_tests_timeout.test.jsnew file mode 100644index 0000000000..73de9aedf0--- /dev/null+++ b/tests/ui_tests/test_run_all_tests_timeout.test.js@@ -0,0 +1,79 @@+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { after, test } = require('node:test');++const { runTest } = require('./run_all_tests');++const fixtureDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ldr-ui-runner-'));+after(() => fs.rmSync(fixtureDir, { recursive: true, force: true }));++function fixture(name, source) {+ const file = path.join(fixtureDir, name);+ fs.writeFileSync(file, source);+ return { name, file };+}++// runTest() prints the same "Running", "Test timeout", PASSED/FAILED and+// "TIMING:" lines for these fixtures as for real UI tests, and this file runs+// in the error-benchmark shard. Hold those lines back and print them only if a+// case fails, so a search of the shard log finds only real test results.+async function runFixture(t, child, timeoutMs, check) {+ const log = t.mock.method(console, 'log', () => {});+ let result;+ try {+ result = await runTest(child, timeoutMs);+ } finally {+ log.mock.restore();+ }+ try {+ check(result);+ } catch (error) {+ const lines = log.mock.calls.map((call) => call.arguments.join(' '));+ console.log(`runTest output for ${child.name}:\n${lines.join('\n')}`);+ throw error;+ }+}++test('a completed child passes', async (t) => {+ await runFixture(t, fixture('success.js', 'process.exit(0);'), 5000, (result) => {+ assert.equal(result.success, true);+ });+});++test('a timed-out child that exits zero on SIGTERM fails', async (t) => {+ const child = fixture(+ 'clean-shutdown.js',+ 'process.on("SIGTERM", () => process.exit(0)); setInterval(() => {}, 1000);'+ );+ // Allow a loaded CI host time to start Node before the SIGTERM handler is installed.+ await runFixture(t, child, 3000, (result) => {+ assert.equal(result.code, 0);+ assert.equal(result.success, false);+ assert.match(result.error, /Timed out/);+ });+});++// The child ignores SIGTERM and exits on its own after 20 s, so a runner that+// never escalates to SIGKILL fails this test instead of leaving the child alive.+test('a timed-out child that ignores SIGTERM is killed and fails', async (t) => {+ const child = fixture(+ 'ignore-sigterm.js',+ 'process.on("SIGTERM", () => {}); setTimeout(() => process.exit(0), 20000);'+ );+ // Same startup allowance as above; the runner sends SIGKILL 5 s after SIGTERM.+ await runFixture(t, child, 3000, (result) => {+ assert.equal(result.signal, 'SIGKILL');+ assert.equal(result.code, null);+ assert.equal(result.success, false);+ assert.match(result.error, /Timed out/);+ });+});++test('a child that exits nonzero fails', async (t) => {+ await runFixture(t, fixture('failure.js', 'process.exit(1);'), 5000, (result) => {+ assert.equal(result.success, false);+ assert.equal(result.code, 1);+ });+});