diff --git a/CHANGELOG.md b/CHANGELOG.md index 38b0f7d37bb..ab9c78d9c02 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ### Notable fixes - **Updates — pads no longer call `/api/version-status` when `updates.tier` is `"off"` (#8573).** The server does not register that endpoint when the tier is off, but the pad still requested it on every load, leaving a 404 in the browser's network tab. The server now sends `clientVars.updateCheck: false` and the pad skips the request. Other tiers are unchanged. Reported by @n-goncalves. +- **Admin UI — no more `/admin/update/status` request when `updates.tier` is `"off"` (#8573).** The server does not register that route when the tier is off, but the admin banner and update page still requested it. The admin UI now reads the tier from its settings socket and skips the request. Instead it shows a notice that update notifications are turned off, so you may not hear about security updates, with how to turn them back on (`updates.tier` in `settings.json` or the `UPDATES_TIER` environment variable) and a link to the update docs. The notice can be dismissed for the browser session. The troubleshooting page also stops showing "Update available: undefined" when `privacy.updateCheck` is `false`. Other tiers are unchanged. # 3.3.22 diff --git a/admin/src/App.tsx b/admin/src/App.tsx index 97f000fd162..7f71b5dd5de 100644 --- a/admin/src/App.tsx +++ b/admin/src/App.tsx @@ -78,6 +78,9 @@ export const App = () => { if (settings && typeof settings.flags === 'object' && settings.flags) { useStore.getState().setGdprAuthorErasureEnabled( !!settings.flags.gdprAuthorErasure); + if (typeof settings.flags.updatesTier === 'string') { + useStore.getState().setUpdatesTier(settings.flags.updatesTier); + } } if (settings.results === 'NOT_ALLOWED') { console.log('Not allowed to view settings.json') @@ -92,6 +95,12 @@ export const App = () => { useStore.getState().setShowLoading(false); }); + // Sent by the server on every connect, even when settings.json can't be + // read. The update banner and page wait for it (issue #8573). + settingSocket.on('updatesTier', (tier: unknown) => { + if (typeof tier === 'string') useStore.getState().setUpdatesTier(tier); + }); + settingSocket.on('saveprogress', (status: string, payload?: {message?: string}) => { const {setToastState} = useStore.getState(); if (status === 'saved') { diff --git a/admin/src/components/UpdateBanner.tsx b/admin/src/components/UpdateBanner.tsx index 177035ef817..b55fb38de4c 100644 --- a/admin/src/components/UpdateBanner.tsx +++ b/admin/src/components/UpdateBanner.tsx @@ -1,7 +1,15 @@ import {useEffect, useState} from 'react'; -import {Link} from 'react-router-dom'; +import {Link, useLocation} from 'react-router-dom'; import {Trans, useTranslation} from 'react-i18next'; import {useStore} from '../store/store'; +import {UpdatesOffNotice} from './UpdatesOffNotice'; + +// Dismissal lasts for the browser session only, so an admin who turned +// updates off is reminded again next time they sign in. +const OFF_DISMISS_KEY = 'etherpad.admin.updatesOffNoticeDismissed'; +const readDismissed = (): boolean => { + try { return window.sessionStorage.getItem(OFF_DISMISS_KEY) === '1'; } catch { return false; } +}; const fmtRemaining = (ms: number): string => { if (ms <= 0) return '0s'; @@ -15,15 +23,22 @@ export const UpdateBanner = () => { const {t} = useTranslation(); const updateStatus = useStore((s) => s.updateStatus); const setUpdateStatus = useStore((s) => s.setUpdateStatus); + const updatesTier = useStore((s) => s.updatesTier); + const [offDismissed, setOffDismissed] = useState(readDismissed); + // The update page renders the same notice itself; don't show it twice. + const onUpdatePage = useLocation().pathname.replace(/\/+$/, '').endsWith('/update'); useEffect(() => { + // Wait for the tier from the /settings socket. With tier "off" the + // server does not register the status route, so do not request it. + if (updatesTier == null || updatesTier === 'off') return; let cancelled = false; fetch('/admin/update/status', {credentials: 'same-origin'}) .then((r) => r.ok ? r.json() : null) .then((data) => { if (data && !cancelled) setUpdateStatus(data); }) .catch(() => {}); return () => { cancelled = true; }; - }, [setUpdateStatus]); + }, [setUpdateStatus, updatesTier]); const scheduledFor = updateStatus?.execution?.status === 'scheduled' ? (updateStatus.execution as {scheduledFor: string}).scheduledFor @@ -38,6 +53,16 @@ export const UpdateBanner = () => { return () => clearInterval(id); }, [scheduledFor]); + if (updatesTier === 'off') { + if (offDismissed || onUpdatePage) return null; + return ( + { + try { window.sessionStorage.setItem(OFF_DISMISS_KEY, '1'); } catch {/* noop */} + setOffDismissed(true); + }}/> + ); + } + if (!updateStatus) return null; // Terminal rollback-failed wins over the regular "update available" banner — diff --git a/admin/src/components/UpdatesOffNotice.tsx b/admin/src/components/UpdatesOffNotice.tsx new file mode 100644 index 00000000000..dd732e69885 --- /dev/null +++ b/admin/src/components/UpdatesOffNotice.tsx @@ -0,0 +1,37 @@ +import {Trans, useTranslation} from 'react-i18next'; + +// Shown instead of the update banner / update page when updates.tier is +// "off" (issue #8573). The server does not register /admin/update/status in +// that case, so the UI must not request it; instead it explains the setting +// and how to turn update notifications back on. +// +// The URL is assembled at runtime on purpose: behind a reverse proxy the +// server rewrites every literal "/admin" in the admin bundle to +// "/admin", which would corrupt an external docs link. +export const UPDATES_DOCS_URL = new URL('admin/updates.html', 'https://docs.etherpad.org/').href; + +export const UpdatesOffNotice = ({onDismiss}: {onDismiss?: () => void}) => { + const {t} = useTranslation(); + return ( +
+
+ {t('update.page.disabled')}{' '} + {t('update.off.body')}{' '} + + }} + /> + {' '} + + {t('update.off.docs')} + +
+ {onDismiss && ( + + )} +
+ ); +}; diff --git a/admin/src/index.css b/admin/src/index.css index 29413dee9f3..e4932e1da4b 100644 --- a/admin/src/index.css +++ b/admin/src/index.css @@ -869,6 +869,33 @@ input, button, select, optgroup, textarea { font-weight: 500; } +/* updates.tier "off": informational, not a warning colour (#8573). */ +.update-banner-off { + align-items: flex-start; + justify-content: space-between; + background: #eef6fc; + color: #1f3a52; + border-color: #b9d8f0; + border-left: 4px solid #0ea5e9; + line-height: 1.5; +} +.update-banner-off code { + font-size: 13px; + padding: 0 3px; + background: rgba(14, 165, 233, .12); + border-radius: 3px; +} +.update-banner-dismiss { + flex: none; + background: transparent; + border: 1px solid currentColor; + border-radius: 4px; + color: inherit; + font-size: 13px; + padding: 2px 8px; + cursor: pointer; +} + /* Update page layout. */ .update-page { padding: 16px 0; } .update-page h1 { margin-bottom: 16px; } diff --git a/admin/src/pages/HelpPage.tsx b/admin/src/pages/HelpPage.tsx index c1dfa5efc4f..d92a511f086 100644 --- a/admin/src/pages/HelpPage.tsx +++ b/admin/src/pages/HelpPage.tsx @@ -45,8 +45,12 @@ export const HelpPage = () => { const totalBindings = hooks.reduce((n, h) => n + h.parts.length, 0) - const updateAvailable = helpData - ? helpData.epVersion.localeCompare(helpData.latestVersion, undefined, {numeric: true}) < 0 + // latestVersion is missing when privacy.updateCheck is false (or the + // legacy check has not finished); don't report "update available: undefined". + const latestKnown = !!helpData?.latestVersion + const versionCheckOff = helpData?.versionCheck === false + const updateAvailable = helpData && latestKnown + ? helpData.epVersion.localeCompare(helpData.latestVersion!, undefined, {numeric: true}) < 0 : false const copyDiag = () => { @@ -89,17 +93,24 @@ export const HelpPage = () => {
{helpData.epVersion}
-
- - {updateAvailable - ? t('admin_plugins_info.update_available', {version: helpData.latestVersion}) - : t('admin_plugins_info.up_to_date')} -
+ {versionCheckOff ? ( +
+ + }}/> +
+ ) : latestKnown && ( +
+ + {updateAvailable + ? t('admin_plugins_info.update_available', {version: helpData.latestVersion}) + : t('admin_plugins_info.up_to_date')} +
+ )}
-
{helpData.latestVersion}
+
{helpData.latestVersion ?? '—'}
diff --git a/admin/src/pages/Plugin.ts b/admin/src/pages/Plugin.ts index d7f3b23a7fb..44e498cc2e7 100644 --- a/admin/src/pages/Plugin.ts +++ b/admin/src/pages/Plugin.ts @@ -53,5 +53,8 @@ export type HelpObj = { installedParts: string[], installedPlugins: string[], installedServerHooks: Record, - latestVersion: string + // Missing when privacy.updateCheck is false or the check has not finished. + latestVersion?: string, + // False when privacy.updateCheck is false (the latest version is never fetched). + versionCheck?: boolean, } diff --git a/admin/src/pages/UpdatePage.tsx b/admin/src/pages/UpdatePage.tsx index f8d6c51acdc..f248c3233bc 100644 --- a/admin/src/pages/UpdatePage.tsx +++ b/admin/src/pages/UpdatePage.tsx @@ -1,6 +1,7 @@ -import {useEffect, useState} from 'react'; +import {useEffect, useRef, useState} from 'react'; import {Trans, useTranslation} from 'react-i18next'; import {useStore} from '../store/store'; +import {UpdatesOffNotice} from '../components/UpdatesOffNotice'; type FetchState = | {kind: 'loading'} @@ -25,17 +26,27 @@ export const UpdatePage = () => { const setUpdateStatus = useStore((s) => s.setUpdateStatus); const log = useStore((s) => s.updateLog); const setLog = useStore((s) => s.setUpdateLog); + const updatesTier = useStore((s) => s.updatesTier); + // Read inside async callbacks so a request that was started before the + // tier turned "off" can't overwrite the notice or keep polling. + const tierRef = useRef(updatesTier); + tierRef.current = updatesTier; + const tierOff = () => tierRef.current === 'off'; // Self-fetch so the page renders an explicit state even if UpdateBanner's - // best-effort fetch never landed (route returns 404 when tier=off, 401/403 - // if requireAdminForStatus is set, or a transient network error). + // best-effort fetch never landed (401/403 if requireAdminForStatus is set, + // or a transient network error). Tier "off" never reaches the fetch: the + // tier comes from the /settings socket (issue #8573). const [fetchState, setFetchState] = useState(us ? {kind: 'ok'} : {kind: 'loading'}); const [actionInFlight, setActionInFlight] = useState(false); const refreshStatus = async () => { + if (tierOff()) return; try { const r = await fetch('/admin/update/status', {credentials: 'same-origin'}); + if (tierOff()) return; if (r.ok) { const data = await r.json(); + if (tierOff()) return; setUpdateStatus(data); setFetchState({kind: 'ok'}); } else if (r.status === 404) { @@ -46,25 +57,34 @@ export const UpdatePage = () => { setFetchState({kind: 'error', status: r.status}); } } catch { + if (tierOff()) return; setFetchState({kind: 'error', status: 0}); } }; useEffect(() => { + // The tier comes from the /settings socket. Until it arrives, keep + // loading. With tier "off" the status route is not registered, so show + // the notice without requesting it (issue #8573). + if (updatesTier == null) return; + if (updatesTier === 'off') { + setFetchState({kind: 'disabled'}); + return; + } let cancelled = false; void refreshStatus().then(() => { if (cancelled) return; }); return () => { cancelled = true; }; // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); + }, [updatesTier]); // Poll log + status while the executor is in flight, then stop. const status = us?.execution?.status ?? 'idle'; const inFlight = IN_FLIGHT_STATUSES.includes(status); useEffect(() => { - if (!inFlight) return; + if (!inFlight || updatesTier === 'off') return; let cancelled = false; const tick = async () => { - if (cancelled) return; + if (cancelled || tierOff()) return; try { const lr = await fetch('/admin/update/log', {credentials: 'same-origin'}); if (lr.ok) setLog(await lr.text()); @@ -75,7 +95,7 @@ export const UpdatePage = () => { void tick(); return () => { cancelled = true; }; // eslint-disable-next-line react-hooks/exhaustive-deps - }, [inFlight]); + }, [inFlight, updatesTier]); const post = async (path: string) => { setActionInFlight(true); @@ -114,7 +134,7 @@ export const UpdatePage = () => { return (

-

{t('update.page.disabled', {defaultValue: 'Update checks are disabled (updates.tier = "off").'})}

+
); } diff --git a/admin/src/store/store.ts b/admin/src/store/store.ts index 74a3815dce3..b4209ad7320 100644 --- a/admin/src/store/store.ts +++ b/admin/src/store/store.ts @@ -92,6 +92,11 @@ type StoreState = { setAuthors: (authors: AuthorSearchResult)=>void, gdprAuthorErasureEnabled: boolean, setGdprAuthorErasureEnabled: (enabled: boolean)=>void, + // updates.tier as reported by the /settings socket. null until the first + // `settings` payload arrives; the update UI waits for it so it never + // requests /admin/update/status when the tier is "off". + updatesTier: string | null, + setUpdatesTier: (tier: string | null) => void, } @@ -125,6 +130,8 @@ export const useStore = create()((set) => ({ setAuthors: (authors)=>set({authors}), gdprAuthorErasureEnabled: false, setGdprAuthorErasureEnabled: (gdprAuthorErasureEnabled)=>set({gdprAuthorErasureEnabled}), + updatesTier: null, + setUpdatesTier: (updatesTier) => set({updatesTier}), })); export const useResolvedAt = (path: JSONPath): unknown => diff --git a/doc/admin/updates.md b/doc/admin/updates.md index 83b882c9c4f..9c401e1d36a 100644 --- a/doc/admin/updates.md +++ b/doc/admin/updates.md @@ -104,6 +104,8 @@ The notice auto-fades after 8 seconds and can be dismissed immediately. The publ Set `updates.tier` to `"off"`. The self-updater goes silent — no request to the GitHub Releases API leaves the instance and no banner or badge renders. `GET /api/version-status` is not registered, and the pad client does not request it either: the server sends `clientVars.updateCheck: false`, so the browser's network tab shows no version-status call. Note this does **not** cover the separate legacy version check in `UpdateCheck.ts`, which still fetches `${updateServer}/info.json` until you also set `privacy.updateCheck` to `false` (see [PRIVACY.md](https://github.com/ether/etherpad/blob/develop/PRIVACY.md)). +With the tier off, the admin UI does not request `/admin/update/status` either. It learns the tier from its admin settings socket and shows a notice instead: update notifications are turned off, so you may not hear about security updates. The notice names the setting to change (`updates.tier` in `settings.json`, or the `UPDATES_TIER` environment variable) and links to this page. Admins can dismiss it for the rest of the browser session. To turn update notifications back on, set `updates.tier` to `"notify"` (or a higher tier) and restart Etherpad. If `privacy.updateCheck` is `false`, the admin troubleshooting page says the latest-version check is off instead of showing a latest version. + On Docker / air-gapped installs you can do both without editing `settings.json` inside the image by setting `UPDATES_TIER=off` **and** `PRIVACY_UPDATE_CHECK=false` (add `PRIVACY_PLUGIN_CATALOG=false` to also disable the admin plugin browser's catalogue fetch). See the [Updates & privacy](../docker.md#updates--privacy-offline--air-gapped) table in the Docker docs for the full set of environment variables. ## Privacy diff --git a/src/locales/en.json b/src/locales/en.json index fbc722f1a1d..ee5a0762501 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -123,6 +123,7 @@ "admin_plugins_info.tab_server": "Server", "admin_plugins_info.up_to_date": "Up to date", "admin_plugins_info.update_available": "Update available: {{version}}", + "admin_plugins_info.version_check_off": "Latest-version check is off (privacy.updateCheck is false)", "admin_plugins_info.version": "Etherpad version", "admin_plugins_info.version_latest": "Latest available version", "admin_plugins_info.version_number": "Version number", @@ -178,6 +179,10 @@ "update.page.changelog": "Changelog", "update.page.up_to_date": "You are running the latest version.", "update.page.disabled": "Update checks are disabled (updates.tier = \"off\").", + "update.off.body": "This admin panel will not tell you about new Etherpad releases, so you may not hear about security updates.", + "update.off.howto": "To turn update notifications back on, set updates.tier to \"notify\" in settings.json (or set the UPDATES_TIER environment variable) and restart Etherpad.", + "update.off.docs": "Read the update documentation", + "update.off.dismiss": "Dismiss", "update.page.unauthorized": "You are not authorised to view update status.", "update.page.error": "Could not load update status (status {{status}}).", "update.badge.severe": "Etherpad on this server is severely outdated. Tell your admin.", diff --git a/src/node/hooks/express/adminsettings.ts b/src/node/hooks/express/adminsettings.ts index d52b07a6869..45da67f2b23 100644 --- a/src/node/hooks/express/adminsettings.ts +++ b/src/node/hooks/express/adminsettings.ts @@ -81,6 +81,12 @@ exports.socketio = (hookName: string, {io}: any) => { return; } + // Sent on connect, independent of `load`: `load` emits nothing when the + // settings file can't be read (e.g. running on defaults without + // settings.json), and the update UI waits for the tier before it does + // anything (issue #8573). + socket.emit('updatesTier', settings.updates.tier); + socket.on('load', async (query: string): Promise => { let data; try { @@ -91,6 +97,10 @@ exports.socketio = (hookName: string, {io}: any) => { const flags = { gdprAuthorErasure: !!(settings.gdprAuthorErasure && settings.gdprAuthorErasure.enabled), + // The admin UI reads the tier from here instead of probing + // /admin/update/status, which is not registered when the tier is + // "off" (issue #8573). Sent only to admin sockets. + updatesTier: settings.updates.tier, }; if (settings.showSettingsInAdminPage === false) { socket.emit('settings', {results: 'NOT_ALLOWED', flags}); @@ -161,6 +171,9 @@ exports.socketio = (hookName: string, {io}: any) => { installedServerHooks: mapToObject(hooks), installedClientHooks: mapToObject(clientHooks), latestVersion: getLatestVersion(), + // False when privacy.updateCheck is off: latestVersion is then never + // known, so the help page must not claim the install is up to date. + versionCheck: settings.privacy.updateCheck !== false, }) }); diff --git a/src/tests/backend/specs/admin/updatesTierFlag.ts b/src/tests/backend/specs/admin/updatesTierFlag.ts new file mode 100644 index 00000000000..a288af783a3 --- /dev/null +++ b/src/tests/backend/specs/admin/updatesTierFlag.ts @@ -0,0 +1,151 @@ +'use strict'; + +import {strict as assert} from 'assert'; +import path from 'path'; +import setCookieParser from 'set-cookie-parser'; + +const io = require('socket.io-client'); +const common = require('../../common'); +const settings = require('../../../../node/utils/Settings'); + +// Issue #8573: with updates.tier "off" the server does not register +// /admin/update/status, so the admin UI learns the tier from the /settings +// socket's `settings` payload (flags.updatesTier) and skips that request. +// The help payload also says whether privacy.updateCheck is on, so the help +// page does not claim "update available: undefined" when it is off. +const adminSocket = async () => { + settings.users = settings.users || {}; + settings.users['test-admin'] = {password: 'test-admin-password', is_admin: true}; + const savedRequireAuthentication = settings.requireAuthentication; + settings.requireAuthentication = true; + let res: any; + try { + res = await (common.agent as any) + .get('/admin/') + .auth('test-admin', 'test-admin-password'); + } finally { + settings.requireAuthentication = savedRequireAuthentication; + } + const resCookies = setCookieParser.parse(res, {map: true}); + const reqCookieHdr = Object.entries(resCookies) + .map(([name, cookie]: [string, any]) => + `${name}=${encodeURIComponent(cookie.value)}`) + .join('; '); + const socket = io(`${common.baseUrl}/settings`, { + forceNew: true, + query: {cookie: reqCookieHdr}, + }); + // The server emits `updatesTier` as soon as the connection is accepted. + socket.tierOnConnect = new Promise((resolve) => socket.once('updatesTier', resolve)); + await new Promise((resolve, reject) => { + socket.once('connect', resolve); + socket.once('connect_error', reject); + }); + return socket; +}; + +const ask = (socket: any, evt: string, replyEvt: string, budgetMs = 10000) => + new Promise((resolve, reject) => { + const timer = setTimeout( + () => reject(new Error(`no ${replyEvt} reply within ${budgetMs}ms`)), budgetMs); + socket.once(replyEvt, (data: any) => { clearTimeout(timer); resolve(data); }); + socket.emit(evt); + }); + +describe(__filename, function () { + this.timeout(60000); + let socket: any; + let savedUsers: any; + let savedTier: string; + let savedUpdateCheck: boolean; + let savedSettingsFilename: string; + let setupCompleted = false; + + before(async function () { + await common.init(); + savedUsers = settings.users; + savedTier = settings.updates.tier; + savedUpdateCheck = settings.privacy.updateCheck; + savedSettingsFilename = settings.settingsFilename; + // `load` reads the settings file from disk; CI has no settings.json, so + // point it at the template for the duration of this suite. + settings.settingsFilename = path.join(settings.root, 'settings.json.template'); + setupCompleted = true; + try { + socket = await adminSocket(); + // An authenticate-hook plugin can refuse the plain-text test admin + // (see anonymizeAuthorSocket.ts); skip rather than hang in that case. + await ask(socket, 'load', 'settings', 15000); + } catch (err: any) { + console.warn(`[updatesTierFlag] admin socket unavailable (${err?.message}); skipping`); + this.skip(); + } + }); + + after(function () { + if (socket) socket.disconnect(); + if (!setupCompleted) return; + settings.updates.tier = savedTier; + settings.privacy.updateCheck = savedUpdateCheck; + settings.settingsFilename = savedSettingsFilename; + if (settings.users) delete settings.users['test-admin']; + settings.users = savedUsers; + }); + + for (const tier of ['off', 'notify', 'manual', 'auto', 'autonomous']) { + it(`settings payload reports flags.updatesTier = "${tier}"`, async function () { + settings.updates.tier = tier; + const payload = await ask(socket, 'load', 'settings'); + assert.equal(payload.flags.updatesTier, tier); + }); + } + + it('reports flags.updatesTier even when the settings page is hidden', async function () { + const saved = settings.showSettingsInAdminPage; + settings.showSettingsInAdminPage = false; + settings.updates.tier = 'off'; + try { + const payload = await ask(socket, 'load', 'settings'); + assert.equal(payload.results, 'NOT_ALLOWED'); + assert.equal(payload.flags.updatesTier, 'off'); + } finally { + settings.showSettingsInAdminPage = saved; + } + }); + + it('emits updatesTier on connect even when settings.json cannot be read', async function () { + settings.updates.tier = 'off'; + settings.settingsFilename = path.join(settings.root, 'var', 'does-not-exist.json'); + const s2 = await adminSocket(); + try { + const tier = await Promise.race([ + s2.tierOnConnect, + new Promise((_, rej) => setTimeout(() => rej(new Error('no updatesTier on connect')), 10000)), + ]); + assert.equal(tier, 'off'); + } finally { + s2.disconnect(); + settings.settingsFilename = path.join(settings.root, 'settings.json.template'); + } + }); + + it('help payload reports versionCheck: false when privacy.updateCheck is off', async function () { + settings.privacy.updateCheck = false; + const help = await ask(socket, 'help', 'reply:help'); + assert.equal(help.versionCheck, false); + assert.equal(help.latestVersion, undefined); + }); + + it('help payload reports versionCheck: true by default', async function () { + // getLatestVersion() kicks off the legacy fetch; keep it off the network. + const savedServer = settings.updateServer; + settings.updateServer = 'http://127.0.0.1:9'; + settings.privacy.updateCheck = true; + try { + const help = await ask(socket, 'help', 'reply:help'); + assert.equal(help.versionCheck, true); + } finally { + settings.updateServer = savedServer; + } + }); +}); diff --git a/src/tests/frontend-new/admin-spec/update-tier-off.spec.ts b/src/tests/frontend-new/admin-spec/update-tier-off.spec.ts new file mode 100644 index 00000000000..eadc8630bbd --- /dev/null +++ b/src/tests/frontend-new/admin-spec/update-tier-off.spec.ts @@ -0,0 +1,133 @@ +import {expect, Page, test} from "@playwright/test"; +import {loginToAdmin} from "../helper/adminhelper"; + +// Issue #8573: with updates.tier "off" the server does not register +// /admin/update/status. The admin UI learns the tier from the /settings +// socket (flags.updatesTier) and must not request the status route; it shows +// a notice explaining the setting instead. The CI server runs the default +// "notify" tier, so the tier is rewritten to "off" on the socket. The same +// is done for the help payload's versionCheck (privacy.updateCheck). + +const NS = '/settings'; +const PREFIX = `42${NS},`; + +const parseFrame = (msg: string | Buffer) => { + if (typeof msg !== 'string' || !msg.startsWith(PREFIX)) return null; + const m = /^(\d*)(\[[\s\S]*)$/.exec(msg.slice(PREFIX.length)); + if (!m) return null; + return {ack: m[1], payload: JSON.parse(m[2]) as unknown[]}; +}; + +const forceUpdatesOff = async (page: Page) => { + await page.routeWebSocket(/\/socket\.io\//, (ws) => { + const server = ws.connectToServer(); + ws.onMessage((msg) => server.send(msg)); + server.onMessage((msg) => { + const frame = parseFrame(msg); + // Sent on connect; the UI acts on whichever tier arrives first. + if (frame && frame.payload[0] === 'updatesTier') { + frame.payload[1] = 'off'; + ws.send(`${PREFIX}${frame.ack}${JSON.stringify(frame.payload)}`); + return; + } + if (frame && frame.payload[0] === 'settings') { + const data = frame.payload[1] as {flags?: Record}; + data.flags = {...(data.flags ?? {}), updatesTier: 'off'}; + ws.send(`${PREFIX}${frame.ack}${JSON.stringify(frame.payload)}`); + return; + } + if (frame && frame.payload[0] === 'reply:help') { + const data = frame.payload[1] as Record; + data.versionCheck = false; + delete data.latestVersion; + ws.send(`${PREFIX}${frame.ack}${JSON.stringify(frame.payload)}`); + return; + } + ws.send(msg); + }); + }); +}; + +const recordStatusRequests = (page: Page) => { + const hits: string[] = []; + page.on('request', (req) => { + if (new URL(req.url()).pathname.endsWith('/admin/update/status')) hits.push(req.url()); + }); + return hits; +}; + +const expectNotice = async (page: Page) => { + const notice = page.getByTestId('updates-off-notice').first(); + await expect(notice).toBeVisible({timeout: 30000}); + await expect(notice).toContainText('Update checks are disabled (updates.tier = "off").'); + await expect(notice).toContainText('you may not hear about security updates'); + await expect(notice.locator('code', {hasText: 'updates.tier'})).toBeVisible(); + await expect(notice.locator('code', {hasText: 'UPDATES_TIER'})).toBeVisible(); + const docs = notice.getByRole('link', {name: 'Read the update documentation'}); + await expect(docs).toHaveAttribute('href', 'https://docs.etherpad.org/admin/updates.html'); + return notice; +}; + +test.describe('admin UI with updates.tier "off"', () => { + let statusHits: string[]; + + test.beforeEach(async ({page}) => { + await forceUpdatesOff(page); + statusHits = recordStatusRequests(page); + await loginToAdmin(page, 'admin', 'changeme1'); + }); + + test('banner explains the setting and never requests /admin/update/status', async ({page}) => { + await page.goto('http://localhost:9001/admin/'); + await expectNotice(page); + if (process.env.UPDATES_OFF_SCREENSHOT) { + await page.screenshot({path: process.env.UPDATES_OFF_SCREENSHOT, fullPage: false}); + } + // Give a late fetch time to show up before asserting there was none. + await page.waitForTimeout(1000); + expect(statusHits).toEqual([]); + }); + + test('banner can be dismissed for the session', async ({page}) => { + await page.goto('http://localhost:9001/admin/'); + const notice = await expectNotice(page); + await notice.getByRole('button', {name: 'Dismiss'}).click(); + await expect(page.getByTestId('updates-off-notice')).toHaveCount(0); + await page.reload(); + await expect(page.getByRole('link', {name: /etherpad updates/i})).toBeVisible({timeout: 30000}); + await expect(page.getByTestId('updates-off-notice')).toHaveCount(0); + }); + + test('update page shows the notice and never requests /admin/update/status', async ({page}) => { + await page.goto('http://localhost:9001/admin/update'); + await expect(page.getByRole('heading', {name: /etherpad updates/i})).toBeVisible({timeout: 30000}); + await expectNotice(page); + // Only the page's own notice, not the banner's copy as well. + await expect(page.getByTestId('updates-off-notice')).toHaveCount(1); + await expect(page.getByTestId('updates-off-notice').getByRole('button', {name: 'Dismiss'})) + .toHaveCount(0); + await page.waitForTimeout(1000); + expect(statusHits).toEqual([]); + }); + + test('help page says the latest-version check is off', async ({page}) => { + await page.goto('http://localhost:9001/admin/help'); + const off = page.getByTestId('version-check-off'); + await expect(off).toBeVisible({timeout: 30000}); + await expect(off).toContainText('Latest-version check is off'); + await expect(off.locator('code')).toHaveText('privacy.updateCheck'); + await expect(page.getByText(/update available: undefined/i)).toHaveCount(0); + }); + + test('docs link survives the reverse-proxy "/admin" rewrite', async ({request}) => { + // Behind a proxy the server rewrites every "/admin" in the bundle to + // "/admin". The docs URL must not contain that literal. + const headers = {'x-proxy-path': '/sub'}; + const html = await (await request.get('http://localhost:9001/admin/', {headers})).text(); + const src = /src="\/sub(\/admin\/assets\/index-[^"]+\.js)"/.exec(html)?.[1]; + expect(src, 'admin bundle script tag').toBeTruthy(); + const js = await (await request.get(`http://localhost:9001${src}`, {headers})).text(); + expect(js).toContain('admin/updates.html'); + expect(js).not.toContain('docs.etherpad.org/sub'); + }); +});