BlueGit

timfa filemanager

Files

filemanager / tests / admin.routes.test.js

admin.routes.test.js

admin.routes.test.js 17.5 KiB Download Raw
1'use strict';
2
3/**
4 * Unit tests for server/routes/admin.js — user CRUD and config management.
5 */
6
7const express = require('express');
8const http = require('http');
9const { once } = require('events');
10const crypto = require('crypto');
11const fs = require('fs');
12const os = require('os');
13const path = require('path');
14
15// ── child_process mock — controlled per test ──────────────────────────────────
16let mockExecFileImpl = null;
17jest.mock('child_process', () =>
18{
19 const real = jest.requireActual('child_process');
20 return {
21 ...real,
22 execFile: jest.fn((...args) =>
23 {
24 const cb = args[args.length - 1];
25 if (typeof mockExecFileImpl === 'function')
26 {
27 mockExecFileImpl(...args);
28 return;
29 }
30 // Default: simulate git not available.
31 cb(new Error('git not found'));
32 }),
33 };
34});
35
36// ── in-memory DB mock ───────────────────────────────────────────────────────
37jest.mock('../server/db', () =>
38{
39 const { Database } = require('node-sqlite3-wasm');
40 let db;
41 function getDb ()
42 {
43 if (!db)
44 {
45 db = new Database(':memory:');
46 db.exec(`
47 CREATE TABLE IF NOT EXISTS users (
48 id INTEGER PRIMARY KEY AUTOINCREMENT,
49 username TEXT UNIQUE NOT NULL,
50 password_hash TEXT NOT NULL,
51 is_admin INTEGER NOT NULL DEFAULT 0,
52 permissions TEXT NOT NULL DEFAULT '{}'
53 );
54 CREATE TABLE IF NOT EXISTS file_meta (
55 file_path TEXT PRIMARY KEY,
56 uploader TEXT NOT NULL DEFAULT '',
57 downloaders TEXT NOT NULL DEFAULT '[]'
58 );
59 `);
60 }
61 return db;
62 }
63 return { getDb, initDb: getDb };
64});
65
66// ── config mock ─────────────────────────────────────────────────────────────
67const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'], userPath: null };
68jest.mock('../server/config', () => ({
69 loadConfig: () => ({ ...mockConfig }),
70 saveConfig: (c) => Object.assign(mockConfig, c),
71 getEffectivePaths: (p) => p,
72 getAllowedRoot: () => null,
73}));
74
75// ── auth mock — bypass JWT verification ─────────────────────────────────────
76let mockUser = { id: 1, username: 'admin', isAdmin: true, permissions: {} };
77jest.mock('../server/auth', () => ({
78 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
79 requireAdmin: (req, res, next) =>
80 {
81 if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin required.' });
82 next();
83 },
84 createToken: () => 'mock-token',
85 getClientIp: () => '127.0.0.1',
86 getRegion: () => 'US:CA',
87}));
88
89const adminRoutes = require('../server/routes/admin');
90const { getDb } = require('../server/db');
91const bcrypt = require('bcrypt');
92
93jest.setTimeout(30000);
94
95// ── seed a default admin before anything runs ────────────────────────────────
96beforeAll(() =>
97{
98 const db = getDb();
99 const hash = bcrypt.hashSync('admin1234', 4); // low rounds for speed
100 db.prepare('INSERT OR IGNORE INTO users (username, password_hash, is_admin, permissions) VALUES (?,?,1,?)')
101 .run(['admin', hash, '{}']);
102});
103
104// ── build minimal app ────────────────────────────────────────────────────────
105let server;
106let baseUrl;
107let shutdownForRestartMock;
108
109beforeAll(async () =>
110{
111 const app = express();
112 shutdownForRestartMock = jest.fn();
113 app.set('shutdownForRestart', shutdownForRestartMock);
114 app.use(express.json());
115 app.use('/api/admin', adminRoutes);
116 app.use((err, req, res, next) =>
117 {
118 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
119 });
120 server = http.createServer(app);
121 server.listen(0);
122 await once(server, 'listening');
123 baseUrl = `http://127.0.0.1:${server.address().port}`;
124});
125
126afterAll(() => server.close());
127
128// ── helpers ──────────────────────────────────────────────────────────────────
129function req (method, path, body)
130{
131 const payload = body ? JSON.stringify(body) : undefined;
132 return new Promise((resolve, reject) =>
133 {
134 const r = http.request(baseUrl + path, {
135 method,
136 headers: {
137 'Content-Type': 'application/json',
138 ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
139 },
140 }, res =>
141 {
142 let data = '';
143 res.on('data', d => data += d);
144 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
145 });
146 r.on('error', reject);
147 if (payload) r.write(payload);
148 r.end();
149 });
150}
151
152// ── tests ─────────────────────────────────────────────────────────────────────
153
154describe('GET /api/admin/users', () =>
155{
156 test('returns the list of users', async () =>
157 {
158 const { status, body } = await req('GET', '/api/admin/users');
159 expect(status).toBe(200);
160 expect(Array.isArray(body.users)).toBe(true);
161 expect(body.users[0]).toMatchObject({ username: 'admin', isAdmin: true });
162 });
163});
164
165describe('POST /api/admin/users', () =>
166{
167 test('creates a new user', async () =>
168 {
169 const { status, body } = await req('POST', '/api/admin/users', {
170 username: 'bob', password: 'bobpass1', isAdmin: false, permissions: {},
171 });
172 expect(status).toBe(201);
173 expect(body.ok).toBe(true);
174 });
175
176 test('rejects duplicate username', async () =>
177 {
178 const { status } = await req('POST', '/api/admin/users', {
179 username: 'bob', password: 'bobpass2', isAdmin: false, permissions: {},
180 });
181 expect(status).toBe(409);
182 });
183
184 test('rejects duplicate username with different case', async () =>
185 {
186 const { status } = await req('POST', '/api/admin/users', {
187 username: 'BoB', password: 'bobpass3', isAdmin: false, permissions: {},
188 });
189 expect(status).toBe(409);
190 });
191
192 test('rejects short password', async () =>
193 {
194 const { status } = await req('POST', '/api/admin/users', {
195 username: 'carol', password: 'short', isAdmin: false, permissions: {},
196 });
197 expect(status).toBe(400);
198 });
199
200 test('normalizes permissions so write implies read on create', async () =>
201 {
202 const { status } = await req('POST', '/api/admin/users', {
203 username: 'dora',
204 password: 'dora-pass1',
205 isAdmin: false,
206 permissions: { data: { read: false, write: true } },
207 });
208 expect(status).toBe(201);
209
210 const { body } = await req('GET', '/api/admin/users');
211 const dora = body.users.find(u => u.username === 'dora');
212 expect(dora.permissions).toMatchObject({ data: { read: true, write: true } });
213 });
214});
215
216describe('PATCH /api/admin/users/:id', () =>
217{
218 let bobId;
219
220 beforeAll(async () =>
221 {
222 const { body } = await req('GET', '/api/admin/users');
223 bobId = body.users.find(u => u.username === 'bob').id;
224 });
225
226 test('updates permissions', async () =>
227 {
228 const { status, body } = await req('PATCH', `/api/admin/users/${bobId}`, {
229 permissions: { data: { read: true, write: false } },
230 });
231 expect(status).toBe(200);
232 expect(body.ok).toBe(true);
233 });
234
235 test('returns 404 for unknown user', async () =>
236 {
237 const { status } = await req('PATCH', '/api/admin/users/99999', { isAdmin: false });
238 expect(status).toBe(404);
239 });
240
241 test('normalizes permissions so write implies read on update', async () =>
242 {
243 const { status } = await req('PATCH', `/api/admin/users/${bobId}`, {
244 permissions: { data: { read: false, write: true } },
245 });
246 expect(status).toBe(200);
247
248 const { body } = await req('GET', '/api/admin/users');
249 const bob = body.users.find(u => u.id === bobId);
250 expect(bob.permissions).toMatchObject({ data: { read: true, write: true } });
251 });
252
253 test('rejects removing own admin privileges', async () =>
254 {
255 const { status, body } = await req('PATCH', `/api/admin/users/${mockUser.id}`, {
256 isAdmin: false,
257 });
258 expect(status).toBe(400);
259 expect(body.error).toMatch(/own admin privileges/i);
260
261 const usersRes = await req('GET', '/api/admin/users');
262 const me = usersRes.body.users.find(u => String(u.id) === String(mockUser.id));
263 expect(me).toBeTruthy();
264 expect(me.isAdmin).toBe(true);
265 });
266});
267
268describe('DELETE /api/admin/users/:id', () =>
269{
270 let bobId;
271
272 beforeAll(async () =>
273 {
274 const { body } = await req('GET', '/api/admin/users');
275 bobId = body.users.find(u => u.username === 'bob').id;
276 });
277
278 test('cannot delete own account', async () =>
279 {
280 // mock user id is 1 (admin); bob is a different id — but we test self-delete guard
281 const adminId = mockUser.id;
282 const { status } = await req('DELETE', `/api/admin/users/${adminId}`);
283 expect(status).toBe(400);
284 });
285
286 test('deletes another user', async () =>
287 {
288 const { status, body } = await req('DELETE', `/api/admin/users/${bobId}`);
289 expect(status).toBe(200);
290 expect(body.ok).toBe(true);
291 });
292
293 test('cannot delete the last admin', async () =>
294 {
295 // Only 'admin' left; try to delete them (switch mockUser to be different)
296 const { body: users } = await req('GET', '/api/admin/users');
297 const adminUser = users.users.find(u => u.username === 'admin');
298 const { status } = await req('DELETE', `/api/admin/users/${adminUser.id}`);
299 // Our mockUser.id === 1 === adminUser.id, so it should fail with "cannot delete own account"
300 expect([400]).toContain(status);
301 });
302
303 test('deletes an empty personal user folder when deleting that user account', async () =>
304 {
305 const userFolderRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-admin-userfolders-'));
306 mockConfig.userPath = userFolderRoot;
307
308 const db = getDb();
309 const hash = bcrypt.hashSync('freshpass1', 4);
310 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
311 .run(['emptyfolderuser', hash, 0, '{}']);
312
313 const created = db.prepare('SELECT id FROM users WHERE username = ?').get(['emptyfolderuser']);
314 const folderPath = path.join(userFolderRoot, 'emptyfolderuser');
315 fs.mkdirSync(folderPath, { recursive: true });
316
317 try
318 {
319 const { status, body } = await req('DELETE', `/api/admin/users/${created.id}`);
320 expect(status).toBe(200);
321 expect(body.ok).toBe(true);
322 expect(fs.existsSync(folderPath)).toBe(false);
323 } finally
324 {
325 mockConfig.userPath = null;
326 fs.rmSync(userFolderRoot, { recursive: true, force: true });
327 }
328 });
329
330 test('keeps non-empty personal user folder when deleting that user account', async () =>
331 {
332 const userFolderRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-admin-userfolders-'));
333 mockConfig.userPath = userFolderRoot;
334
335 const db = getDb();
336 const hash = bcrypt.hashSync('freshpass2', 4);
337 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
338 .run(['nonemptyuser', hash, 0, '{}']);
339
340 const created = db.prepare('SELECT id FROM users WHERE username = ?').get(['nonemptyuser']);
341 const folderPath = path.join(userFolderRoot, 'nonemptyuser');
342 fs.mkdirSync(folderPath, { recursive: true });
343 fs.writeFileSync(path.join(folderPath, 'keep.txt'), 'keep');
344
345 try
346 {
347 const { status, body } = await req('DELETE', `/api/admin/users/${created.id}`);
348 expect(status).toBe(200);
349 expect(body.ok).toBe(true);
350 expect(fs.existsSync(folderPath)).toBe(true);
351 } finally
352 {
353 mockConfig.userPath = null;
354 fs.rmSync(userFolderRoot, { recursive: true, force: true });
355 }
356 });
357});
358
359describe('GET /api/admin/orphan-userfolders', () =>
360{
361 test('returns only non-empty orphaned folders and deletes empty orphan folders', async () =>
362 {
363 const userFolderRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-admin-userfolders-'));
364 mockConfig.userPath = userFolderRoot;
365
366 const linkedFolder = path.join(userFolderRoot, 'linkeduser');
367 const orphanFolder = path.join(userFolderRoot, 'ghostuser');
368 const emptyOrphanFolder = path.join(userFolderRoot, 'emptyghost');
369
370 fs.mkdirSync(linkedFolder, { recursive: true });
371 fs.mkdirSync(orphanFolder, { recursive: true });
372 fs.mkdirSync(emptyOrphanFolder, { recursive: true });
373 fs.writeFileSync(path.join(orphanFolder, 'file.txt'), 'hello');
374
375 const db = getDb();
376 const hash = bcrypt.hashSync('linked-pass1', 4);
377 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
378 .run(['linkeduser', hash, 0, '{}']);
379
380 try
381 {
382 const { status, body } = await req('GET', '/api/admin/orphan-userfolders');
383 expect(status).toBe(200);
384 expect(Array.isArray(body.folders)).toBe(true);
385 expect(body.folders).toEqual([
386 {
387 folderName: 'ghostuser',
388 path: orphanFolder,
389 itemCount: 1,
390 },
391 ]);
392 expect(fs.existsSync(emptyOrphanFolder)).toBe(false);
393 } finally
394 {
395 mockConfig.userPath = null;
396 fs.rmSync(userFolderRoot, { recursive: true, force: true });
397 }
398 });
399});
400
401describe('GET /api/admin/config', () =>
402{
403 test('returns port and paths', async () =>
404 {
405 const { status, body } = await req('GET', '/api/admin/config');
406 expect(status).toBe(200);
407 expect(body.port).toBe(3000);
408 expect(Array.isArray(body.paths)).toBe(true);
409 });
410});
411
412describe('PUT /api/admin/config', () =>
413{
414 test('saves new paths', async () =>
415 {
416 const { status, body } = await req('PUT', '/api/admin/config', {
417 paths: ['/mnt/newpath'],
418 });
419 expect(status).toBe(200);
420 expect(body.ok).toBe(true);
421 });
422
423 test('rejects non-array paths', async () =>
424 {
425 const { status } = await req('PUT', '/api/admin/config', { paths: 'notanarray' });
426 expect(status).toBe(400);
427 });
428
429 test('rejects invalid port', async () =>
430 {
431 const { status } = await req('PUT', '/api/admin/config', { paths: [], port: 99999 });
432 expect(status).toBe(400);
433 });
434});
435
436describe('POST /api/admin/shutdown', () =>
437{
438 test('responds ok and invokes shutdown callback', async () =>
439 {
440 shutdownForRestartMock.mockClear();
441 const { status, body } = await req('POST', '/api/admin/shutdown');
442 expect(status).toBe(200);
443 expect(body.ok).toBe(true);
444
445 // Shutdown invocation is deferred via setImmediate().
446 await new Promise(resolve => setImmediate(resolve));
447 expect(shutdownForRestartMock).toHaveBeenCalledTimes(1);
448 });
449});
450
451describe('GET /api/admin/update-status', () =>
452{
453 const origInvocationId = process.env.INVOCATION_ID;
454
455 afterEach(() =>
456 {
457 mockExecFileImpl = null;
458 if (origInvocationId === undefined)
459 delete process.env.INVOCATION_ID;
460 else
461 process.env.INVOCATION_ID = origInvocationId;
462 });
463
464 test('returns underSystemd=false when INVOCATION_ID is not set', async () =>
465 {
466 delete process.env.INVOCATION_ID;
467 const { status, body } = await req('GET', '/api/admin/update-status');
468 expect(status).toBe(200);
469 expect(body.underSystemd).toBe(false);
470 expect(body.commitsAhead).toEqual([]);
471 });
472
473 test('returns underSystemd=true and commitsAhead when INVOCATION_ID is set and git reports commits', async () =>
474 {
475 process.env.INVOCATION_ID = 'test-invocation-id';
476 // git fetch succeeds, then git log returns two commits.
477 let callCount = 0;
478 let logArgs = null;
479 mockExecFileImpl = (_cmd, _args, _opts, cb) =>
480 {
481 callCount++;
482 if (callCount === 1) cb(null, { stdout: '', stderr: '' }); // git fetch
483 else
484 {
485 logArgs = _args;
486 cb(null, {
487 stdout: 'abc1234567890\x1fFix bug\x1fThis fixes an issue users were hitting.\x1e'
488 + 'def5678901234\x1fAdd feature\x1fUsers can now do the new thing.\x1e',
489 stderr: '',
490 });
491 }
492 };
493 const { status, body } = await req('GET', '/api/admin/update-status');
494 expect(status).toBe(200);
495 expect(body.underSystemd).toBe(true);
496 expect(logArgs).toContain('--no-merges');
497 expect(body.commitsAhead).toEqual([
498 {
499 hash: 'abc1234567890',
500 subject: 'Fix bug',
501 body: 'This fixes an issue users were hitting.',
502 },
503 {
504 hash: 'def5678901234',
505 subject: 'Add feature',
506 body: 'Users can now do the new thing.',
507 },
508 ]);
509 });
510
511 test('returns underSystemd=true and empty commitsAhead when git is up to date', async () =>
512 {
513 process.env.INVOCATION_ID = 'test-invocation-id';
514 let callCount = 0;
515 mockExecFileImpl = (_cmd, _args, _opts, cb) =>
516 {
517 callCount++;
518 cb(null, { stdout: '', stderr: '' }); // fetch and log both return empty
519 };
520 const { status, body } = await req('GET', '/api/admin/update-status');
521 expect(status).toBe(200);
522 expect(body.underSystemd).toBe(true);
523 expect(body.commitsAhead).toEqual([]);
524 });
525
526 test('returns underSystemd=true and empty commitsAhead when git fails', async () =>
527 {
528 process.env.INVOCATION_ID = 'test-invocation-id';
529 mockExecFileImpl = (_cmd, _args, _opts, cb) =>
530 {
531 cb(new Error('git: not found'));
532 };
533 const { status, body } = await req('GET', '/api/admin/update-status');
534 expect(status).toBe(200);
535 expect(body.underSystemd).toBe(true);
536 expect(body.commitsAhead).toEqual([]);
537 });
538});