Skip to content

~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.

test(ui): validate signed-out login and protected-page flows (#7007)

LearningCircuitf159965e9419
diff --git a/tests/ui_tests/test_auth_comprehensive_ci.js b/tests/ui_tests/test_auth_comprehensive_ci.js
index fb092980ee..aafc7907ac 100644
--- a/tests/ui_tests/test_auth_comprehensive_ci.js
+++ b/tests/ui_tests/test_auth_comprehensive_ci.js
@@ -7,161 +7,92 @@
* Run: node test_auth_comprehensive_ci.js
*/
-const { setupTest, teardownTest, TestResults, log, delay, navigateTo, withTimeout } = require('./test_lib');
+const { setupTest, teardownTest, TestResults, log, delay, navigateTo, withTimeout, withFreshBrowserContext } = require('./test_lib');
// ============================================================================
// Login Page Tests
// ============================================================================
+const LOGIN_FORM = 'form[action*="/auth/login"]';
+
+async function navigateToLogin(page, baseUrl) {
+ // Always load the document: navigateTo() intentionally reuses the current
+ // path, which could leave a previous failed-login response in this check.
+ const response = await page.goto(`${baseUrl}/auth/login`, { waitUntil: 'domcontentloaded' });
+ const actual = new URL(page.url());
+ if (response?.status() !== 200 || actual.origin !== new URL(baseUrl).origin
+ || actual.pathname !== '/auth/login') {
+ throw new Error(`Expected the login page, got HTTP ${response?.status()} at ${page.url()}`);
+ }
+}
+
const LoginPageTests = {
async loginFormElements(page, baseUrl) {
- await navigateTo(page, `${baseUrl}/auth/login`);
- await delay(500); // Extra wait for CI
-
- const result = await page.evaluate(() => {
- const form = document.querySelector('form');
- const usernameInput = document.querySelector('input[name="username"], input[type="text"], #username');
- const passwordInput = document.querySelector('input[name="password"], input[type="password"], #password');
- const submitBtn = document.querySelector('button[type="submit"], input[type="submit"], .btn-primary');
- const registerLink = document.querySelector('a[href*="register"]');
-
+ await navigateToLogin(page, baseUrl);
+ const result = await page.evaluate((selector) => {
+ const form = document.querySelector(selector);
+ const username = form?.querySelector('input[name="username"]');
+ const password = form?.querySelector('input[name="password"]');
+ const submit = form?.querySelector('button[type="submit"], input[type="submit"]');
+ const visible = (element) => !!element && element.getClientRects().length > 0
+ && getComputedStyle(element).visibility !== 'hidden';
return {
- hasForm: !!form,
- hasUsername: !!usernameInput,
- hasPassword: !!passwordInput,
- hasSubmit: !!submitBtn,
- hasRegisterLink: !!registerLink,
- usernameType: usernameInput?.type,
- passwordType: passwordInput?.type,
- submitText: submitBtn?.textContent?.trim()
+ hasForm: !!form && form.method === 'post'
+ && new URL(form.action).pathname === '/auth/login',
+ hasUsername: visible(username) && username.type === 'text',
+ hasPassword: visible(password) && password.type === 'password',
+ hasSubmit: visible(submit) && !submit.disabled,
+ submitText: submit?.textContent?.trim() || submit?.value,
};
- });
-
- // In CI, if we don't find key elements, skip instead of fail
- if (!result.hasForm || !result.hasUsername) {
- return { passed: null, skipped: true, message: 'Login form not found (may require different auth flow)' };
- }
-
- // If password field not found, skip instead of fail - it might be hidden or use different structure
- if (!result.hasPassword) {
- return { passed: null, skipped: true, message: 'Password field not visible (may use different login flow)' };
- }
- const passed = result.hasForm && result.hasUsername && result.hasPassword && result.hasSubmit;
+ }, LOGIN_FORM);
return {
- passed: true,
- message: `Login form complete (username=${result.usernameType}, password=${result.passwordType}, submit="${result.submitText}")`
+ passed: result.hasForm && result.hasUsername && result.hasPassword && result.hasSubmit,
+ message: `Login form: username=${result.hasUsername}, password=${result.hasPassword}, submit=${result.hasSubmit} ("${result.submitText}")`,
};
},
async loginEmptyFieldValidation(page, baseUrl) {
- await navigateTo(page, `${baseUrl}/auth/login`);
- await delay(300);
-
- // Try to submit empty form
- const result = await page.evaluate(() => {
- const submitBtn = document.querySelector('button[type="submit"], input[type="submit"], .btn-primary');
- const usernameInput = document.querySelector('input[name="username"], input[type="text"], #username');
- const passwordInput = document.querySelector('input[name="password"], input[type="password"], #password');
-
- if (!usernameInput || !passwordInput) {
- return { notFound: true };
- }
-
- // Check if fields have required attribute
- const usernameRequired = usernameInput?.required || usernameInput?.hasAttribute('required');
- const passwordRequired = passwordInput?.required || passwordInput?.hasAttribute('required');
-
- // Try clicking submit
- if (submitBtn) submitBtn.click();
-
+ await navigateToLogin(page, baseUrl);
+ await page.click(`${LOGIN_FORM} button[type="submit"]`);
+ const result = await page.evaluate((selector) => {
+ const form = document.querySelector(selector);
+ const username = form?.querySelector('input[name="username"]');
+ const password = form?.querySelector('input[name="password"]');
return {
- usernameRequired,
- passwordRequired,
- usernameValid: usernameInput?.validity?.valid,
- passwordValid: passwordInput?.validity?.valid
+ usernameMissing: username?.validity.valueMissing === true,
+ passwordMissing: password?.validity.valueMissing === true,
};
- });
-
- if (result.notFound) {
- return { passed: null, skipped: true, message: 'Login form fields not found' };
- }
-
- const hasValidation = result.usernameRequired || result.passwordRequired ||
- result.usernameValid === false || result.passwordValid === false;
-
- // Skip instead of fail - server-side validation is also valid
- if (!hasValidation) {
- return { passed: null, skipped: true, message: 'No client-side empty field validation (may use server-side validation)' };
- }
-
+ }, LOGIN_FORM);
return {
- passed: true,
- message: `Empty field validation present (username required=${result.usernameRequired}, password required=${result.passwordRequired})`
+ passed: result.usernameMissing && result.passwordMissing
+ && new URL(page.url()).pathname === '/auth/login',
+ message: `Empty login fields refused (username=${result.usernameMissing}, password=${result.passwordMissing})`,
};
},
async loginInvalidCredentials(page, baseUrl) {
- await navigateTo(page, `${baseUrl}/auth/login`);
- await delay(300);
-
- // Check if we have the login form
- const hasForm = await page.evaluate(() => {
- return !!document.querySelector('input[name="username"], input[type="text"], #username');
- });
-
- if (!hasForm) {
- return { passed: null, skipped: true, message: 'Login form not found for invalid credentials test' };
- }
-
- // Submit with invalid credentials
- await page.evaluate(() => {
- const usernameInput = document.querySelector('input[name="username"], input[type="text"], #username');
- const passwordInput = document.querySelector('input[name="password"], input[type="password"], #password');
-
- if (usernameInput) usernameInput.value = 'invalid_user_12345';
- if (passwordInput) passwordInput.value = 'wrong_password_12345';
- });
-
- // Submit the form
- await Promise.all([
- page.click('button[type="submit"], input[type="submit"], .btn-primary'),
- page.waitForNavigation({ waitUntil: 'domcontentloaded', timeout: 10000 }).catch(() => {})
+ await navigateToLogin(page, baseUrl);
+ await page.type(`${LOGIN_FORM} input[name="username"]`, `invalid_user_${Date.now()}`);
+ await page.type(`${LOGIN_FORM} input[name="password"]`, 'wrong_password_12345');
+ const [response] = await Promise.all([
+ page.waitForNavigation({ waitUntil: 'domcontentloaded' }),
+ page.click(`${LOGIN_FORM} button[type="submit"]`),
]);
-
- await delay(1000); // Extra delay for error message to appear
-
- const result = await page.evaluate(() => {
- // Look for error messages
- const errorElement = document.querySelector('.alert-danger, .error, .flash-error, [class*="error"], [role="alert"], .ldr-alert');
- const flashMessage = document.querySelector('.flash, .message, .notification');
- const pageText = document.body.textContent?.toLowerCase() || '';
-
- return {
- hasErrorElement: !!errorElement,
- hasFlashMessage: !!flashMessage,
- errorText: errorElement?.textContent?.trim()?.substring(0, 100),
- containsErrorText: pageText.includes('invalid') || pageText.includes('incorrect') ||
- pageText.includes('wrong') || pageText.includes('failed'),
- stillOnLogin: window.location.href.includes('login')
- };
- });
-
- // If we're still on login page, that counts as handling invalid credentials
- const hasErrorHandling = result.hasErrorElement || result.hasFlashMessage ||
- result.containsErrorText || result.stillOnLogin;
-
- // Skip instead of fail if error handling not detected - it might be using JavaScript validation
- if (!hasErrorHandling) {
- return { passed: null, skipped: true, message: 'Invalid credentials handling not detected (may use JavaScript/async validation)' };
- }
-
+ const errorText = await page.$$eval('.ldr-auth-container .alert', (alerts) =>
+ alerts.filter((element) => element.getClientRects().length > 0
+ && getComputedStyle(element).visibility !== 'hidden')
+ .map((element) => element.textContent.trim())
+ .find((text) => /invalid username or password/i.test(text)) || ''
+ );
+ const passed = response?.status() === 401 && response.request().method() === 'POST'
+ && new URL(page.url()).pathname === '/auth/login' && errorText.length > 0;
return {
- passed: true,
- message: `Invalid credentials handled (error shown: "${result.errorText || 'stayed on login page'}")`
+ passed,
+ message: `Invalid login returned HTTP ${response?.status()} with visible credential error: "${errorText}"`,
};
},
async loginRememberMeCheckbox(page, baseUrl) {
- await navigateTo(page, `${baseUrl}/auth/login`);
+ await navigateToLogin(page, baseUrl);
const result = await page.evaluate(() => {
const rememberMe = document.querySelector('input[name="remember"], input[name="remember_me"], #remember, #remember_me');
@@ -190,7 +121,7 @@ const LoginPageTests = {
});
if (!result.hasRememberMe) {
- return { passed: null, skipped: true, message: 'No remember me checkbox found' };
+ return { passed: false, message: 'Remember me checkbox is missing from the login page' };
}
return {
@@ -200,7 +131,7 @@ const LoginPageTests = {
},
async loginNavigateToRegister(page, baseUrl) {
- await navigateTo(page, `${baseUrl}/auth/login`);
+ await navigateToLogin(page, baseUrl);
await delay(300);
const result = await page.evaluate(() => {
@@ -591,28 +522,29 @@ const SessionTests = {
},
async protectedPageRedirect(page, baseUrl) {
- // Clear cookies to ensure logged out
- const client = await page.target().createCDPSession();
- await client.send('Network.clearBrowserCookies');
-
- // Try to access a protected page
- await navigateTo(page, `${baseUrl}/settings`);
+ // Request the protected page from a new browser context instead of
+ // clearing this page's cookies: a response to a request this page
+ // sent before the clear can put the session cookie back (see
+ // withFreshBrowserContext). This page also stays signed in.
+ return withFreshBrowserContext(page, async (freshPage) => {
+ const response = await freshPage.goto(`${baseUrl}/settings`, { waitUntil: 'domcontentloaded' });
+
+ // Judge the server's answer (a redirect chain ending on the login
+ // page, or a 401/403), not where the page's scripts may move the
+ // browser after it loads.
+ const finalUrl = response ? response.url() : freshPage.url();
+ const status = response?.status();
+ const serverRedirected = !!response && response.request().redirectChain().length > 0;
+ const redirectedToLogin = status === 401 || status === 403
+ || (serverRedirected && new URL(finalUrl).pathname === '/auth/login');
- const result = await page.evaluate(() => {
- const url = window.location.href;
- const hasLoginForm = !!document.querySelector('input[name="password"]');
return {
- url,
- redirectedToLogin: url.includes('login') || hasLoginForm
+ passed: redirectedToLogin,
+ message: redirectedToLogin
+ ? 'Protected pages redirect to login'
+ : `No redirect for protected page (stayed at ${finalUrl}, status: ${status})`
};
});
-
- return {
- passed: result.redirectedToLogin,
- message: result.redirectedToLogin
- ? 'Protected pages redirect to login'
- : `No redirect for protected page (stayed at ${result.url})`
- };
}
};
@@ -667,38 +599,39 @@ async function main() {
const { baseUrl } = ctx.config;
try {
- // Login Page Tests
+ // Each login test starts signed out, independently of the signed-in
+ // page used for registration, session and password-change checks.
log.section('Login Page');
- const loginFormResult = await LoginPageTests.loginFormElements(page, baseUrl);
+ const loginFormResult = await withFreshBrowserContext(page, (loginPage) => LoginPageTests.loginFormElements(loginPage, baseUrl));
if (loginFormResult.skipped) {
results.skip('Login', 'Form Elements', loginFormResult.message);
} else {
results.add('Login', 'Form Elements', loginFormResult.passed, loginFormResult.message);
}
- const loginValidationResult = await LoginPageTests.loginEmptyFieldValidation(page, baseUrl);
+ const loginValidationResult = await withFreshBrowserContext(page, (loginPage) => LoginPageTests.loginEmptyFieldValidation(loginPage, baseUrl));
if (loginValidationResult.skipped) {
results.skip('Login', 'Empty Field Validation', loginValidationResult.message);
} else {
results.add('Login', 'Empty Field Validation', loginValidationResult.passed, loginValidationResult.message);
}
- const loginInvalidResult = await LoginPageTests.loginInvalidCredentials(page, baseUrl);
+ const loginInvalidResult = await withFreshBrowserContext(page, (loginPage) => LoginPageTests.loginInvalidCredentials(loginPage, baseUrl));
if (loginInvalidResult.skipped) {
results.skip('Login', 'Invalid Credentials Handling', loginInvalidResult.message);
} else {
results.add('Login', 'Invalid Credentials Handling', loginInvalidResult.passed, loginInvalidResult.message);
}
- const rememberMeResult = await LoginPageTests.loginRememberMeCheckbox(page, baseUrl);
+ const rememberMeResult = await withFreshBrowserContext(page, (loginPage) => LoginPageTests.loginRememberMeCheckbox(loginPage, baseUrl));
if (rememberMeResult.skipped) {
results.skip('Login', 'Remember Me Checkbox', rememberMeResult.message);
} else {
results.add('Login', 'Remember Me Checkbox', rememberMeResult.passed, rememberMeResult.message);
}
- const registerLinkResult = await LoginPageTests.loginNavigateToRegister(page, baseUrl);
+ const registerLinkResult = await withFreshBrowserContext(page, (loginPage) => LoginPageTests.loginNavigateToRegister(loginPage, baseUrl));
if (registerLinkResult.skipped) {
results.skip('Login', 'Navigate to Register', registerLinkResult.message);
} else {
@@ -763,8 +696,11 @@ async function main() {
const protectedResult = await SessionTests.protectedPageRedirect(page, baseUrl);
results.add('Session', 'Protected Page Redirect', protectedResult.passed, protectedResult.message);
- // Re-authenticate for remaining tests (cap at 30s — if the server is
- // slow after session tests, skip password tests rather than hang for 300s)
+ // Make sure this page is signed in for the remaining tests. The
+ // protected-page check above uses its own browser context and does
+ // not sign this page out, so this normally finds it still signed in.
+ // Cap at 30s — if the server is slow after session tests, skip
+ // password tests rather than hang for 300s.
let reAuthOk = false;
try {
await withTimeout(
@@ -792,6 +728,7 @@ async function main() {
}
} catch (error) {
+ results.add('Suite', 'Execution', false, error.message);
log.error(`Fatal error: ${error.message}`);
console.error(error.stack);
} finally {
diff --git a/tests/ui_tests/test_error_and_session_ux_ci.js b/tests/ui_tests/test_error_and_session_ux_ci.js
index f6229971f7..04d5fafd2e 100644
--- a/tests/ui_tests/test_error_and_session_ux_ci.js
+++ b/tests/ui_tests/test_error_and_session_ux_ci.js
@@ -25,8 +25,9 @@
* fixed; Test 2 is the regression pin -- see below).
* - test_error_handling_ci.js's `Error401Tests.unauthenticatedRedirectsToLogin`
* and test_download_and_csrf_flows_ci.js's Test 7 ("logout invalidates
- * access to an authenticated page") both clear cookies/log out and
- * then do a FRESH FULL-PAGE NAVIGATION to a protected route, which
+ * access to an authenticated page") both do a FRESH FULL-PAGE
+ * NAVIGATION to a protected route without a valid session (from a new,
+ * cookieless browser context / after logging out), which
* exercises the server-side HTML-route redirect
* (`_register_exception_handlers`'s 401 handler -> 302 to
* /auth/login) -- a request that never runs any app JS at all. This
diff --git a/tests/ui_tests/test_error_handling_ci.js b/tests/ui_tests/test_error_handling_ci.js
index c15737c1e2..df6460d2ab 100644
--- a/tests/ui_tests/test_error_handling_ci.js
+++ b/tests/ui_tests/test_error_handling_ci.js
@@ -7,7 +7,7 @@
* Run: node test_error_handling_ci.js
*/
-const { setupTest, teardownTest, TestResults, log, delay, navigateTo, withTimeout } = require('./test_lib');
+const { setupTest, teardownTest, TestResults, log, delay, navigateTo, withTimeout, withFreshBrowserContext } = require('./test_lib');
/**
* Navigate with a single retry on timeout.
@@ -142,74 +142,76 @@ const Error404Tests = {
// ============================================================================
// 401 Authentication Error Tests
// ============================================================================
+// Both checks send their requests from a new browser context
+// (withFreshBrowserContext) and leave the signed-in page alone. They used to
+// clear the signed-in page's cookies over CDP, which was flaky: the server
+// re-sends the session cookie on authenticated responses, so a response to a
+// request the page had sent before the clear could put the cookie back. In
+// CI this showed up as the protected-route check failing right after the
+// clear, and as the re-login after it finding no login form, because
+// /auth/login redirects a browser that is still signed in.
const Error401Tests = {
async unauthenticatedRedirectsToLogin(page, baseUrl) {
- // Navigate to login page first to avoid pending XHR interference
- await page.goto(`${baseUrl}/auth/login`, { waitUntil: 'domcontentloaded', timeout: 15000 });
-
- // Clear cookies to simulate unauthenticated state
- const client = await page.target().createCDPSession();
- await client.send('Network.clearBrowserCookies');
+ return withFreshBrowserContext(page, async (freshPage) => {
+ const response = await freshPage.goto(`${baseUrl}/settings/`, { waitUntil: 'domcontentloaded' });
+ if (!response) {
+ return { passed: false, message: 'No response for /settings/' };
+ }
- await navigateTo(page, `${baseUrl}/settings/`);
-
- const result = await page.evaluate(() => {
- const currentPath = window.location.pathname;
- const hasLoginForm = !!document.querySelector('form[action*="login"], input[type="password"], .login-form');
- const bodyText = document.body.textContent?.toLowerCase() || '';
- const hasLoginText = bodyText.includes('login') || bodyText.includes('sign in');
+ // Judge the server's own answer. page.goto() follows redirects and
+ // returns the last response, so a server-side redirect to the
+ // login page shows up as a non-empty redirect chain ending on
+ // /auth/login. A 200 /settings/ page whose scripts later move the
+ // browser to /auth/login does not count.
+ const redirects = response.request().redirectChain()
+ .map((request) => `${request.response()?.status()} ${new URL(request.url()).pathname}`);
+ const status = response.status();
+ const finalPath = new URL(response.url()).pathname;
+ const redirectedToLogin = redirects.length > 0 && finalPath === '/auth/login';
+ const passed = status === 401 || status === 403 || redirectedToLogin;
+ const details = `redirects: [${redirects.join(', ')}], final: ${status} ${finalPath}`;
return {
- currentPath,
- redirectedToLogin: currentPath.includes('login') || currentPath.includes('auth'),
- hasLoginForm,
- hasLoginText
+ passed,
+ message: passed
+ ? `Unauthenticated /settings/ request denied (${details})`
+ : `Protected route accessible without authentication (${details})`
};
});
-
- const passed = result.redirectedToLogin || result.hasLoginForm || result.hasLoginText;
-
- return {
- passed,
- message: passed
- ? `Unauthenticated user redirected to login (path: ${result.currentPath})`
- : 'Protected route accessible without authentication'
- };
},
async apiUnauthorizedReturns401(page, baseUrl) {
- // Clear cookies
- const client = await page.target().createCDPSession();
- await client.send('Network.clearBrowserCookies');
-
- await navigateTo(page, `${baseUrl}/`);
+ return withFreshBrowserContext(page, async (freshPage) => {
+ // fetch() needs a same-origin document; the login page is public.
+ await freshPage.goto(`${baseUrl}/auth/login`, { waitUntil: 'domcontentloaded' });
+
+ const result = await freshPage.evaluate(async (url) => {
+ try {
+ const response = await fetch(`${url}/api/history`);
+ return {
+ status: response.status,
+ redirected: response.redirected,
+ finalPath: new URL(response.url).pathname
+ };
+ } catch (e) {
+ return { error: e.message };
+ }
+ }, baseUrl);
- const result = await page.evaluate(async (url) => {
- try {
- const response = await fetch(`${url}/api/history`);
- return {
- status: response.status,
- is401or403: response.status === 401 || response.status === 403,
- redirected: response.redirected,
- finalUrl: response.url
- };
- } catch (e) {
- return { error: e.message };
+ if (result.error) {
+ return { passed: null, skipped: true, message: `API call failed: ${result.error}` };
}
- }, baseUrl);
- if (result.error) {
- return { passed: null, skipped: true, message: `API call failed: ${result.error}` };
- }
-
- const passed = result.is401or403 || result.redirected;
+ const passed = result.status === 401 || result.status === 403
+ || (result.redirected && result.finalPath === '/auth/login');
- return {
- passed,
- message: passed
- ? `Unauthenticated API returns ${result.status} or redirects`
- : `API accessible without auth (status: ${result.status})`
- };
+ return {
+ passed,
+ message: passed
+ ? `Unauthenticated API request denied (status: ${result.status}, path: ${result.finalPath})`
+ : `API accessible without auth (status: ${result.status}, path: ${result.finalPath})`
+ };
+ });
}
};
@@ -218,9 +220,6 @@ const Error401Tests = {
// ============================================================================
const ApiErrorTests = {
async apiMissingParamsReturns400(page, baseUrl) {
- // Re-authenticate first
- const ctx = await page.evaluate(() => ({ authenticated: !!document.cookie }));
-
await navigateTo(page, `${baseUrl}/`);
const result = await page.evaluate(async (url) => {
@@ -279,14 +278,17 @@ const ApiErrorTests = {
return { passed: null, skipped: true, message: `API call failed: ${result.error}` };
}
- // Accept 401 as well — auth session may not carry over to the API request
- const passed = result.is404 || result.status === 401;
+ // Only 404 counts. The 401 sub-tests leave this page signed in, so a
+ // 401 here means the session was lost, not that the ID was handled.
+ const passed = result.is404;
return {
passed,
message: passed
? `Invalid research ID returns ${result.status}`
- : `Invalid ID returns ${result.status} (expected 404 or 401)`
+ : result.status === 401
+ ? 'Invalid ID returns 401 (expected 404): the signed-in session was lost'
+ : `Invalid ID returns ${result.status} (expected 404)`
};
}
};
@@ -305,15 +307,13 @@ const RateLimitTests = {
// matched the section heading and made the test never really fail).
await navigateTo(page, `${baseUrl}/metrics/`);
- // The metrics route is @login_required: an unauthenticated request 302s
- // to /auth/login. The 401-auth sub-tests earlier in this suite clear
- // cookies, and on the shared server the re-auth can fail to fully restore
- // a navigable session (the sibling rate-limiting-endpoint test skips on
- // the same 401). Treat a login redirect as an environmental skip — but if
- // we DID land on the metrics page, assert the section strictly (real fail).
+ // The metrics route requires login: an unauthenticated request 302s to
+ // /auth/login. The 401 sub-tests earlier in this suite run in their own
+ // browser context and leave this page signed in, so landing anywhere
+ // but the metrics page is a real failure, not an environmental skip.
const landingPath = page.url();
if (/\/auth\/login/.test(landingPath) || !(await page.$('#metrics'))) {
- return { passed: null, skipped: true, message: `Metrics dashboard not reachable (session lost / redirected): ${landingPath}` };
+ return { passed: false, message: `Metrics dashboard not reachable (session lost / redirected): ${landingPath}` };
}
// Page-specific container present — now require the server-rendered
@@ -397,14 +397,9 @@ const RateLimitTests = {
return { passed: null, skipped: true, message: 'Rate limiting status endpoint not found' };
}
- if (!result.ok && (result.status === 401 || result.status === 403)) {
- return { passed: null, skipped: true, message: `Rate limiting endpoint requires auth (status ${result.status})` };
- }
-
- if (!result.ok && result.error && result.error.startsWith('Non-JSON content-type')) {
- return { passed: null, skipped: true, message: `Rate limiting endpoint returned non-JSON (likely auth redirect)` };
- }
-
+ // A 401/403 or a non-JSON answer (such as a login page) means this
+ // signed-in page lost its session. The 401 sub-tests leave it signed
+ // in, so that is a failure here, not a skip.
return {
passed: result.ok,
message: result.ok
@@ -421,36 +416,53 @@ const FormValidationTests = {
async emptyQueryShowsError(page, baseUrl) {
await navigateTo(page, `${baseUrl}/`);
- // Try to submit empty research form
+ // Submit the research form with an empty query and wait for an error
+ // about the query to become visible. research.js's submit handler runs
+ // FormValidator, which sets aria-invalid on #query and writes the
+ // message into #query-error. Without FormValidator it shows the
+ // message as an alert in #research-alert, and if the request reaches
+ // the server, its "Query is required" answer is shown the same way.
+ //
+ // Only a visible, non-empty message counts, and it must appear after
+ // the click. The page always contains hidden, empty error containers
+ // (#research-error-alert has class ldr-settings-error-container), so
+ // checking that an element matching [class*="error"] exists passed
+ // whatever the form did.
const result = await page.evaluate(() => {
- const form = document.querySelector('form.research-form, form[action*="research"], #research-form');
- const submitBtn = document.querySelector('button[type="submit"], .submit-btn, .btn-primary');
-
- if (!form && !submitBtn) return { hasForm: false };
+ const form = document.querySelector('#research-form');
+ const queryInput = form?.querySelector('#query');
+ const submitBtn = form?.querySelector('#start-research-btn');
+ if (!form || !queryInput || !submitBtn) {
+ return { hasForm: false, path: window.location.pathname };
+ }
- // Clear any existing query
- const queryInput = document.querySelector('input[name*="query"], textarea[name*="query"], #query');
- if (queryInput) queryInput.value = '';
+ const shownText = (el) => {
+ if (!el || el.getClientRects().length === 0) return '';
+ if (getComputedStyle(el).visibility === 'hidden') return '';
+ return (el.textContent || '').trim();
+ };
+ const queryErrorText = () => {
+ if (queryInput.getAttribute('aria-invalid') === 'true') {
+ const text = shownText(document.getElementById(`${queryInput.id}-error`));
+ if (text) return text;
+ }
+ for (const id of ['research-alert', 'research-error-alert']) {
+ const text = shownText(document.getElementById(id)?.querySelector('.alert'));
+ if (/query/i.test(text)) return text;
+ }
+ return '';
+ };
- // Click submit
- if (submitBtn) submitBtn.click();
+ const textBeforeSubmit = queryErrorText();
+ queryInput.value = '';
+ submitBtn.click();
return new Promise(resolve => {
let attempts = 0;
const check = () => {
- const hasError = !!document.querySelector(
- '.error, .invalid-feedback, .form-error, .alert-danger, [class*="error"]'
- );
- const hasInvalidInput = !!document.querySelector('input:invalid, textarea:invalid');
- const errorText = document.querySelector('.error, .invalid-feedback')?.textContent?.trim();
-
- if (hasError || hasInvalidInput || ++attempts >= 15) {
- resolve({
- hasForm: true,
- hasError,
- hasInvalidInput,
- errorText
- });
+ const errorText = queryErrorText();
+ if (errorText || ++attempts >= 15) {
+ resolve({ hasForm: true, textBeforeSubmit, errorText });
} else {
setTimeout(check, 200);
}
@@ -459,17 +471,22 @@ const FormValidationTests = {
});
});
+ // The 401 sub-tests leave this page signed in, so "/" must render the
+ // research form. A missing form is a failure, not a skip.
if (!result.hasForm) {
- return { passed: null, skipped: true, message: 'No research form found' };
+ return { passed: false, message: `No research form found (path: ${result.path})` };
+ }
+ if (result.textBeforeSubmit) {
+ return { passed: false, message: `A query error was already shown before submitting: "${result.textBeforeSubmit}"` };
}
- const passed = result.hasError || result.hasInvalidInput;
+ const passed = !!result.errorText;
return {
passed,
message: passed
- ? `Empty query validation works (error: ${result.errorText || 'shown'})`
- : 'Empty query did not show validation error'
+ ? `Empty query validation works (error: "${result.errorText}")`
+ : 'Empty query did not show a visible error about the query'
};
},
@@ -486,6 +503,23 @@ const FormValidationTests = {
if (!numericInput) return { hasInput: false };
+ // Count only what changes after the bad value: a visible,
+ // non-empty error message that was not shown before, or this
+ // input becoming invalid. Settings pages ship empty error
+ // containers (embedding_settings.html always renders a
+ // .ldr-field-error), which a bare selector match finds whether
+ // or not anything was validated.
+ const shownErrors = () => Array.from(
+ document.querySelectorAll('.error, .invalid-feedback, .form-error, [class*="error"]')
+ )
+ .filter((el) => el.getClientRects().length > 0 && getComputedStyle(el).visibility !== 'hidden')
+ .map((el) => (el.textContent || '').trim())
+ .filter(Boolean);
+ const inputFlagged = () =>
+ numericInput.matches(':invalid') || numericInput.getAttribute('aria-invalid') === 'true';
+ const errorsBefore = new Set(shownErrors());
+ const flaggedBefore = inputFlagged();
+
// Set invalid value
numericInput.value = '-999';
numericInput.dispatchEvent(new Event('change', { bubbles: true }));
@@ -494,16 +528,14 @@ const FormValidationTests = {
return new Promise(resolve => {
let attempts = 0;
const check = () => {
- const hasError = !!document.querySelector(
- '.error, .invalid-feedback, .form-error, [class*="error"]'
- );
- const hasInvalidInput = !!document.querySelector('input:invalid');
+ const newErrors = shownErrors().filter((text) => !errorsBefore.has(text));
+ const inputMarkedInvalid = !flaggedBefore && inputFlagged();
- if (hasError || hasInvalidInput || ++attempts >= 15) {
+ if (newErrors.length > 0 || inputMarkedInvalid || ++attempts >= 15) {
resolve({
hasInput: true,
- hasError,
- hasInvalidInput
+ newErrors,
+ inputMarkedInvalid
});
} else {
setTimeout(check, 200);
@@ -517,12 +549,12 @@ const FormValidationTests = {
return { passed: null, skipped: true, message: 'No numeric input found to test validation' };
}
- const passed = result.hasError || result.hasInvalidInput;
+ const passed = result.newErrors.length > 0 || result.inputMarkedInvalid;
return {
passed,
message: passed
- ? 'Invalid settings value shows validation error'
+ ? `Invalid settings value shows validation error (${result.inputMarkedInvalid ? 'input marked invalid' : `"${result.newErrors[0]}"`})`
: 'Invalid settings value did not trigger validation'
};
},
@@ -604,97 +636,22 @@ async function main() {
await run('404', 'Invalid Research ID Handled', () => Error404Tests.invalidResearchIdHandled(page, baseUrl));
await run('404', 'Invalid Document ID Handled', () => Error404Tests.invalidDocumentIdHandled(page, baseUrl));
- // 401 Authentication Tests
+ // 401 Authentication Tests. Both run in their own browser context, so
+ // the signed-in page used by the rest of the suite keeps its session
+ // and needs no re-login.
log.section('401 Authentication');
await run('401', 'Unauthenticated Redirects To Login', () => Error401Tests.unauthenticatedRedirectsToLogin(page, baseUrl));
-
- // After 401 test cleared cookies, re-authenticate on a fresh login page.
- // We avoid waitForNavigation here — if login fails (CSRF, wrong password),
- // it stays on /auth/login and waitForNavigation hangs for the full timeout.
- // Instead: click submit, then poll for URL change or session cookie.
- let reAuthOk = false;
- try {
- await page.goto(`${baseUrl}/auth/login`, { waitUntil: 'domcontentloaded', timeout: 15000 });
- await page.waitForSelector('input[name="username"]', { timeout: 10000 });
- await page.$eval('input[name="username"]', el => { el.value = ''; });
- await page.$eval('input[name="password"]', el => { el.value = ''; });
- await page.type('input[name="username"]', 'test_admin');
- await page.type('input[name="password"]', 'testpass123');
- await page.click('button[type="submit"]');
-
- // Poll for up to 15s: either we leave /auth/login or get a session cookie
- for (let i = 0; i < 30; i++) {
- await delay(500);
- const url = page.url();
- if (!url.includes('/auth/login')) {
- reAuthOk = true;
- break;
- }
- const cookies = await page.cookies();
- if (cookies.some(c => c.name === 'session')) {
- // Have session cookie but still on login page — navigate away
- await page.goto(baseUrl, { waitUntil: 'domcontentloaded', timeout: 15000 });
- reAuthOk = true;
- break;
- }
- }
- } catch (reAuthError) {
- log.warning(`Direct re-auth failed: ${reAuthError.message}`);
- }
-
- // Fallback: try ensureAuthenticated if direct login failed
- if (!reAuthOk) {
- try {
- await withTimeout(
- ctx.authHelper.ensureAuthenticated(),
- 60000,
- 'Re-authentication after 401 tests'
- );
- reAuthOk = true;
- } catch (error) {
- log.warning(`Re-authentication timed out: ${error.message}`);
- }
- }
-
- if (reAuthOk) {
- await run('401', 'API Unauthorized Returns 401', () => Error401Tests.apiUnauthorizedReturns401(page, baseUrl));
- } else {
- results.skip('401', 'API Unauthorized Returns 401', 'Skipped — re-authentication timed out');
- }
-
- // Re-authenticate again for remaining tests
- if (!reAuthOk) {
- try {
- await withTimeout(
- ctx.authHelper.ensureAuthenticated(),
- 60000,
- 'Re-authentication for API tests'
- );
- reAuthOk = true;
- } catch (error) {
- log.warning(`Re-authentication timed out again: ${error.message}`);
- }
- }
+ await run('401', 'API Unauthorized Returns 401', () => Error401Tests.apiUnauthorizedReturns401(page, baseUrl));
// API Error Tests (require authenticated session)
log.section('API Errors');
- if (reAuthOk) {
- await run('API', 'API Missing Params Returns 400', () => ApiErrorTests.apiMissingParamsReturns400(page, baseUrl));
- await run('API', 'API Invalid ID Returns 404', () => ApiErrorTests.apiInvalidIdReturns404(page, baseUrl));
- } else {
- results.skip('API', 'API Missing Params Returns 400', 'Skipped — could not re-authenticate after 401 tests');
- results.skip('API', 'API Invalid ID Returns 404', 'Skipped — could not re-authenticate after 401 tests');
- }
+ await run('API', 'API Missing Params Returns 400', () => ApiErrorTests.apiMissingParamsReturns400(page, baseUrl));
+ await run('API', 'API Invalid ID Returns 404', () => ApiErrorTests.apiInvalidIdReturns404(page, baseUrl));
// Rate Limiting Tests (require authenticated session)
log.section('Rate Limiting');
- if (reAuthOk) {
- await run('RateLimit', 'Rate Limiting Section Renders', () => RateLimitTests.rateLimitingSectionRenders(page, baseUrl));
- await run('RateLimit', 'Rate Limiting Status Endpoint', () => RateLimitTests.rateLimitingStatusEndpoint(page, baseUrl));
- } else {
- results.skip('RateLimit', 'Rate Limiting Section Renders', 'Skipped — could not re-authenticate after 401 tests');
- results.skip('RateLimit', 'Rate Limiting Status Endpoint', 'Skipped — could not re-authenticate after 401 tests');
- }
+ await run('RateLimit', 'Rate Limiting Section Renders', () => RateLimitTests.rateLimitingSectionRenders(page, baseUrl));
+ await run('RateLimit', 'Rate Limiting Status Endpoint', () => RateLimitTests.rateLimitingStatusEndpoint(page, baseUrl));
// Form Validation Tests
log.section('Form Validation');
diff --git a/tests/ui_tests/test_lib/index.js b/tests/ui_tests/test_lib/index.js
index 8d41972a4d..accd38cc75 100644
--- a/tests/ui_tests/test_lib/index.js
+++ b/tests/ui_tests/test_lib/index.js
@@ -42,6 +42,7 @@ const {
delay,
withTimeout,
navigateTo,
+ withFreshBrowserContext,
waitFor,
waitForVisible,
clickAndWaitForNavigation,
@@ -69,6 +70,7 @@ module.exports = {
delay,
withTimeout,
navigateTo,
+ withFreshBrowserContext,
waitFor,
waitForVisible,
clickAndWaitForNavigation,
diff --git a/tests/ui_tests/test_lib/test_utils.js b/tests/ui_tests/test_lib/test_utils.js
index a41447fde8..a9848f7fa6 100644
--- a/tests/ui_tests/test_lib/test_utils.js
+++ b/tests/ui_tests/test_lib/test_utils.js
@@ -198,6 +198,39 @@ async function navigateTo(page, url, options = {}) {
return response;
}
+/**
+ * Run `fn` with a page in a new browser context, then close that context.
+ *
+ * Use this to check what a signed-out visitor gets. A new browser context
+ * starts with its own empty cookie jar, so its requests carry no session
+ * cookie and nothing the signed-in page does can add one. The signed-in page
+ * keeps its session, so the caller does not need to log in again afterwards.
+ *
+ * Clearing the signed-in page's cookies instead is racy. The server re-sends
+ * the session cookie on authenticated responses: for a login without
+ * "Remember me", which is how these tests sign in, DatabaseMiddleware
+ * re-stamps the session's expiry on each response it sends, so Starlette's
+ * SessionMiddleware sends the changed session again. A response to a request
+ * the page sent before the clear can therefore put the session cookie back.
+ *
+ * @param {Object} page - Any page of the browser to use
+ * @param {Function} fn - Async callback that receives the new page
+ * @returns {Promise<*>} The callback's result
+ */
+async function withFreshBrowserContext(page, fn) {
+ const context = await page.browser().createBrowserContext();
+ try {
+ const freshPage = await context.newPage();
+ const timeout = config.isCI ? 60000 : config.timeout;
+ freshPage.setDefaultTimeout(timeout);
+ freshPage.setDefaultNavigationTimeout(timeout);
+ return await fn(freshPage);
+ } finally {
+ // Best effort: a failed close must not hide fn's result or error.
+ await context.close().catch(() => {});
+ }
+}
+
/**
* Wait for an element with better error messages
*
@@ -484,6 +517,7 @@ module.exports = {
delay,
withTimeout,
navigateTo,
+ withFreshBrowserContext,
waitFor,
waitForVisible,
clickAndWaitForNavigation,