Skip to content

Commit abda048

Browse files
JohnMcLearclaude
andauthored
test(docker): admin save persists across container restart (#7819) (#7821)
* test(docker): admin save persists across container restart (#7819) The OP reports the symptom on the official Docker image specifically. Adds two layers of coverage to docker.yml's build-test job, driven from inside a container started against the same TEST_TAG the existing test-container step uses: 1. New mocha spec adminSettings_7819.ts under tests/container/specs/api — authenticates against /admin, opens the /settings socket, saves an augmented JSON with an ep_oauth-shaped top-level block, and asserts the next load reply contains the marker. Intentionally leaves the marker on disk so the workflow can inspect it. 2. docker.yml now `docker exec test grep`s for the marker after test-container, then `docker restart`s the container, waits for the health probe, and re-greps. Both checks must pass — the first proves the socket-driven save actually touched the file inside the container layer; the second proves an in-place restart doesn't reset it. A recreate (docker rm + docker run) would wipe the file, but that's expected (image layer) and out of scope. Container is started with `-e ADMIN_PASSWORD=changeme1` so the existing settings.json.docker provisions the admin user; pad.js doesn't touch /admin so the existing API specs are unaffected. test-container timeout bumped 5s → 30s to cover socket connect + save round-trip, and the mocha discovery extension list now includes `ts` so the new spec is picked up. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test(docker): authenticate via /admin-auth/ POST, surface auth/load failures fast (#7819) CI failed on #7821 with a generic 20s mocha timeout because the spec hit GET /admin/ to grab a session cookie. webaccess.ts only treats paths starting with /admin-auth as requireAdmin — and the container runs with REQUIRE_AUTHENTICATION=false (default), so GET /admin/ never issued a Basic challenge and Set-Cookie was empty. The socket then connected unauthenticated, adminsettings.ts's connection handler returned early without binding any listeners, and the load() promise hung until mocha killed the test with no useful diagnostic. Switch to POST /admin-auth/ (always-requireAdmin, regardless of settings.requireAuthentication). Assert a 2xx with at least one Set-Cookie before proceeding. Add an 8s timeout + meaningful error message to load() so the "session was not admin" failure mode reports immediately instead of burning the suite budget. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test(docker): replace splice with hand-built payload (#7819) Last CI failed because the splice-after-last-} approach landed a comma between an existing trailing-comma-before-comment and the close brace of settings.json.docker, producing `, /* … */, "ep_oauth"` — invalid JSON. settings.json.docker uses jsonc `/* */` and `//` comments and a trailing-comma-before-comment-before-close shape that's annoying to patch from the test side, and the existing isJSONClean has zero backend coverage so the splice is going through Etherpad's lenient write path anyway. Switch to a hand-built minimal-but-viable settings document containing the ep_oauth block. Three properties hold: - We're testing the WRITE path, not the synthesis path. Whatever bytes we send, the next `load` must return verbatim. - The post-save document must survive `docker restart` (the next step in docker.yml) — minimal-but-viable means port/users/dbType are present so Etherpad boots back up and HEALTHCHECK passes. - The next `load` reply must equal the bytes we saved (`reply.results === augmented`) — stronger than `.includes()`. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 49111f2 commit abda048

3 files changed

Lines changed: 193 additions & 2 deletions

File tree

.github/workflows/docker.yml

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,13 @@ jobs:
6666
name: Test
6767
working-directory: etherpad
6868
run: |
69-
docker run --rm -d -p 9001:9001 --name test ${{ env.TEST_TAG }}
69+
# ADMIN_PASSWORD provisions settings.json.docker's admin user so
70+
# the adminSettings_7819 container spec can authenticate against
71+
# /admin and the /settings socket. pad.js doesn't touch /admin
72+
# so the existing API specs are unaffected.
73+
docker run --rm -d -p 9001:9001 \
74+
-e ADMIN_PASSWORD=changeme1 \
75+
--name test ${{ env.TEST_TAG }}
7076
./bin/installDeps.sh
7177
docker logs -f test &
7278
while true; do
@@ -79,6 +85,34 @@ jobs:
7985
esac
8086
done
8187
(cd src && pnpm run test-container)
88+
# Regression for #7819. adminSettings_7819.ts saves a marker via
89+
# the admin /settings socket and intentionally leaves it on
90+
# disk. We assert here that the save actually hit the file
91+
# (mocha only sees the next `load` reply — this catches a
92+
# scenario where the load is served from cache and the file
93+
# never actually changed).
94+
docker exec test grep -q persist-marker-7819 /opt/etherpad-lite/settings.json || {
95+
echo "[#7819] socket-driven save did NOT reach /opt/etherpad-lite/settings.json on disk"
96+
docker exec test cat /opt/etherpad-lite/settings.json | head -50
97+
exit 1
98+
}
99+
# Now prove the on-disk file survives an in-place container
100+
# restart. This is the scenario a docker-compose user with
101+
# `restart: always` hits on every host reboot.
102+
docker restart test >/dev/null
103+
for i in $(seq 1 60); do
104+
status=$(docker container inspect -f '{{.State.Health.Status}}' test 2>/dev/null) || { docker logs test; exit 1; }
105+
case ${status} in
106+
healthy) break;;
107+
starting) sleep 2;;
108+
*) docker logs test; exit 1;;
109+
esac
110+
done
111+
docker exec test grep -q persist-marker-7819 /opt/etherpad-lite/settings.json || {
112+
echo "[#7819 REGRESSION] settings.json was reset on docker restart — ep_oauth block vanished"
113+
docker logs test
114+
exit 1
115+
}
82116
docker rm -f test
83117
git clean -dxf .
84118
-

src/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@
151151
"lint": "eslint .",
152152
"test": "cross-env NODE_ENV=production mocha --import=tsx --require ./tests/backend/diagnostics.ts --timeout 120000 --extension ts --recursive tests/backend/specs ../node_modules/ep_*/static/tests/backend/specs",
153153
"test-utils": "cross-env NODE_ENV=production mocha --import=tsx --timeout 5000 --recursive tests/backend/specs/*utils.ts",
154-
"test-container": "mocha --import=tsx --timeout 5000 tests/container/specs/api",
154+
"test-container": "mocha --import=tsx --timeout 30000 --extension ts,js tests/container/specs/api",
155155
"dev": "cross-env NODE_ENV=development node --require tsx/cjs node/server.ts",
156156
"prod": "cross-env NODE_ENV=production node --require tsx/cjs node/server.ts",
157157
"ts-check": "tsc --noEmit",
Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
'use strict';
2+
3+
// Regression coverage for https://github.com/ether/etherpad/issues/7819.
4+
// Drives the admin /settings socket against the running Docker container
5+
// (test-container target) to prove the save flow actually writes a new
6+
// top-level plugin block and the next `load` reads it back.
7+
//
8+
// Requires the container to be started with `-e ADMIN_PASSWORD=changeme1`
9+
// so settings.json.docker provisions the admin user used here. Run via
10+
// `pnpm run test-container` from the docker.yml workflow.
11+
12+
import {strict as assert} from 'assert';
13+
import setCookieParser from 'set-cookie-parser';
14+
15+
const supertest = require('supertest');
16+
const io = require('socket.io-client');
17+
18+
const BASE_URL = 'http://localhost:9001';
19+
const ADMIN_USER = 'admin';
20+
const ADMIN_PASSWORD = 'changeme1';
21+
const MARKER = 'persist-marker-7819';
22+
23+
// /admin-auth/ is the path webaccess.ts always treats as requireAdmin,
24+
// regardless of settings.requireAuthentication. The container runs with
25+
// REQUIRE_AUTHENTICATION=false (default), so GET /admin/ would NOT issue
26+
// a Basic challenge and we'd never get a session cookie. POSTing to
27+
// /admin-auth/ does.
28+
const adminCookieHeader = async (): Promise<string> => {
29+
const res: any = await supertest(BASE_URL)
30+
.post('/admin-auth/')
31+
.auth(ADMIN_USER, ADMIN_PASSWORD);
32+
if (res.status !== 200) {
33+
throw new Error(
34+
`/admin-auth/ POST returned ${res.status} (expected 200) — ` +
35+
'is the container started with ADMIN_PASSWORD=changeme1? ' +
36+
`Body: ${String(res.text).slice(0, 200)}`);
37+
}
38+
const cookies = setCookieParser.parse(res, {map: true}) as Record<string, any>;
39+
if (Object.keys(cookies).length === 0) {
40+
throw new Error('/admin-auth/ returned 200 but set no cookies — session middleware not wired?');
41+
}
42+
return Object.entries(cookies)
43+
.map(([name, cookie]) => `${name}=${encodeURIComponent(cookie.value)}`)
44+
.join('; ');
45+
};
46+
47+
const settingsSocket = async (cookieHdr: string) => {
48+
const socket = io(`${BASE_URL}/settings`, {
49+
forceNew: true,
50+
query: {cookie: cookieHdr},
51+
transports: ['websocket'],
52+
});
53+
await new Promise<void>((res, rej) => {
54+
const onErr = (err: any) => { socket.off('connect', onConn); rej(err); };
55+
const onConn = () => { socket.off('connect_error', onErr); res(); };
56+
socket.once('connect', onConn);
57+
socket.once('connect_error', onErr);
58+
});
59+
return socket;
60+
};
61+
62+
const load = (socket: any): Promise<{results: string; resolved?: any; flags?: any}> =>
63+
new Promise((res, rej) => {
64+
// No reply == handler never registered, which means our session
65+
// wasn't admin. Surface that fast rather than burning the mocha
66+
// timeout — the adminsettings.ts connection handler silently
67+
// returns without binding any listeners when is_admin is false.
68+
const t = setTimeout(
69+
() => rej(new Error(
70+
'load: no `settings` reply within 8s — likely not authenticated as admin')),
71+
8000);
72+
socket.once('settings', (s: any) => { clearTimeout(t); res(s); });
73+
socket.emit('load', null);
74+
});
75+
76+
const save = (socket: any, payload: string): Promise<{status: string; detail?: any}> =>
77+
new Promise((res, rej) => {
78+
const t = setTimeout(
79+
() => rej(new Error('saveSettings: no saveprogress within 8s')), 8000);
80+
socket.once('saveprogress', (status: string, detail: any) => {
81+
clearTimeout(t);
82+
res({status, detail});
83+
});
84+
socket.emit('saveSettings', payload);
85+
});
86+
87+
describe('admin /settings socket (Docker container) — #7819', function () {
88+
this.timeout(20000);
89+
let socket: any;
90+
91+
before(async function () {
92+
const cookieHdr = await adminCookieHeader();
93+
socket = await settingsSocket(cookieHdr);
94+
// Sanity: load works as admin. We don't keep the result — the file
95+
// we're about to save replaces settings.json entirely.
96+
const reply = await load(socket);
97+
assert.equal(typeof reply.results, 'string',
98+
'settings.results must be a string — container started without ADMIN_PASSWORD?');
99+
});
100+
101+
after(function () {
102+
if (socket) socket.disconnect();
103+
// INTENTIONAL: do NOT restore baseline. docker.yml greps for MARKER
104+
// via `docker exec` after this suite, then runs `docker restart`,
105+
// then greps again — that whole chain proves the on-disk file
106+
// survives container restart, which is the actual #7819 ask. The
107+
// container is `docker rm -f`'d at the end of the workflow step, so
108+
// leftover state doesn't poison anything.
109+
});
110+
111+
it('save → load round-trip preserves a top-level plugin block', async function () {
112+
// Hand-built minimal-but-viable settings document. Three reasons we
113+
// don't splice into the original:
114+
// 1. settings.json.docker uses jsonc `/* */` and `//` comments and
115+
// keeps a trailing-comma-before-comment-before-close pattern
116+
// that's annoying to patch correctly from the test side.
117+
// 2. The backend `saveSettings` handler writes bytes verbatim with
118+
// zero validation — so what we save IS what should come back.
119+
// Whether the payload is "realistic" is orthogonal to whether
120+
// the file persists.
121+
// 3. After this save the container will be `docker restart`ed by
122+
// the workflow. Minimal-but-viable means Etherpad starts back
123+
// up: `port` is required by the HTTP server, `users.admin`
124+
// keeps admin auth working post-restart, dbType=dirty keeps DB
125+
// init happy.
126+
const augmented = JSON.stringify({
127+
title: 'Etherpad',
128+
ip: '0.0.0.0',
129+
port: 9001,
130+
dbType: 'dirty',
131+
dbSettings: {filename: 'var/dirty.db'},
132+
showSettingsInAdminPage: true,
133+
enableAdminUITests: true,
134+
users: {admin: {password: ADMIN_PASSWORD, is_admin: true}},
135+
ep_oauth: {
136+
clientID: MARKER,
137+
clientSecret: 'x',
138+
callbackURL: 'http://x/cb',
139+
},
140+
}, null, 2);
141+
142+
const ack = await save(socket, augmented);
143+
assert.equal(ack.status, 'saved',
144+
`saveSettings did not ack 'saved' — got ${JSON.stringify(ack)}`);
145+
146+
// Re-load over the same socket. adminsettings.ts re-reads
147+
// settings.settingsFilename on every `load`, so this reflects the
148+
// actual file on disk — not a client-side echo.
149+
const reply = await load(socket);
150+
assert.equal(reply.results, augmented,
151+
'load.results must equal the bytes we just saved');
152+
assert.ok(reply.results.includes('"ep_oauth"'),
153+
'ep_oauth block missing from next load — file on disk does not match payload');
154+
assert.ok(reply.results.includes(MARKER),
155+
`marker '${MARKER}' missing from next load`);
156+
});
157+
});

0 commit comments

Comments
 (0)