BlueGit

timfa filemanager

Files

filemanager / tests / admin.routes.test.js

admin.routes.test.js

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