BlueGit

timfa filemanager

Files

filemanager / tests / admin.routes.test.js

admin.routes.test.js

admin.routes.test.js 12.9 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');
11
12// ── child_process mock — controlled per test ──────────────────────────────────
13let mockExecFileImpl = null;
14jest.mock('child_process', () =>
15{
16 const real = jest.requireActual('child_process');
17 return {
18 ...real,
19 execFile: jest.fn((...args) =>
20 {
21 const cb = args[args.length - 1];
22 if (typeof mockExecFileImpl === 'function')
23 {
24 mockExecFileImpl(...args);
25 return;
26 }
27 // Default: simulate git not available.
28 cb(new Error('git not found'));
29 }),
30 };
31});
32
33// ── in-memory DB mock ───────────────────────────────────────────────────────
34jest.mock('../server/db', () =>
35{
36 const { Database } = require('node-sqlite3-wasm');
37 let db;
38 function getDb ()
39 {
40 if (!db)
41 {
42 db = new Database(':memory:');
43 db.exec(`
44 CREATE TABLE IF NOT EXISTS users (
45 id INTEGER PRIMARY KEY AUTOINCREMENT,
46 username TEXT UNIQUE NOT NULL,
47 password_hash TEXT NOT NULL,
48 is_admin INTEGER NOT NULL DEFAULT 0,
49 permissions TEXT NOT NULL DEFAULT '{}'
50 );
51 CREATE TABLE IF NOT EXISTS file_meta (
52 file_path TEXT PRIMARY KEY,
53 uploader TEXT NOT NULL DEFAULT '',
54 downloaders TEXT NOT NULL DEFAULT '[]'
55 );
56 `);
57 }
58 return db;
59 }
60 return { getDb, initDb: getDb };
61});
62
63// ── config mock ─────────────────────────────────────────────────────────────
64const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'] };
65jest.mock('../server/config', () => ({
66 loadConfig: () => ({ ...mockConfig }),
67 saveConfig: (c) => Object.assign(mockConfig, c),
68 getEffectivePaths: (p) => p,
69 getAllowedRoot: () => null,
70}));
71
72// ── auth mock — bypass JWT verification ─────────────────────────────────────
73let mockUser = { id: 1, username: 'admin', isAdmin: true, permissions: {} };
74jest.mock('../server/auth', () => ({
75 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
76 requireAdmin: (req, res, next) =>
77 {
78 if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin required.' });
79 next();
80 },
81 createToken: () => 'mock-token',
82 getClientIp: () => '127.0.0.1',
83 getRegion: () => 'US:CA',
84}));
85
86const adminRoutes = require('../server/routes/admin');
87const { getDb } = require('../server/db');
88const bcrypt = require('bcrypt');
89
90jest.setTimeout(30000);
91
92// ── seed a default admin before anything runs ────────────────────────────────
93beforeAll(() =>
94{
95 const db = getDb();
96 const hash = bcrypt.hashSync('admin1234', 4); // low rounds for speed
97 db.prepare('INSERT OR IGNORE INTO users (username, password_hash, is_admin, permissions) VALUES (?,?,1,?)')
98 .run(['admin', hash, '{}']);
99});
100
101// ── build minimal app ────────────────────────────────────────────────────────
102let server;
103let baseUrl;
104let shutdownForRestartMock;
105
106beforeAll(async () =>
107{
108 const app = express();
109 shutdownForRestartMock = jest.fn();
110 app.set('shutdownForRestart', shutdownForRestartMock);
111 app.use(express.json());
112 app.use('/api/admin', adminRoutes);
113 app.use((err, req, res, next) =>
114 {
115 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
116 });
117 server = http.createServer(app);
118 server.listen(0);
119 await once(server, 'listening');
120 baseUrl = `http://127.0.0.1:${server.address().port}`;
121});
122
123afterAll(() => server.close());
124
125// ── helpers ──────────────────────────────────────────────────────────────────
126function req (method, path, body)
127{
128 const payload = body ? JSON.stringify(body) : undefined;
129 return new Promise((resolve, reject) =>
130 {
131 const r = http.request(baseUrl + path, {
132 method,
133 headers: {
134 'Content-Type': 'application/json',
135 ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
136 },
137 }, res =>
138 {
139 let data = '';
140 res.on('data', d => data += d);
141 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
142 });
143 r.on('error', reject);
144 if (payload) r.write(payload);
145 r.end();
146 });
147}
148
149// ── tests ─────────────────────────────────────────────────────────────────────
150
151describe('GET /api/admin/users', () =>
152{
153 test('returns the list of users', async () =>
154 {
155 const { status, body } = await req('GET', '/api/admin/users');
156 expect(status).toBe(200);
157 expect(Array.isArray(body.users)).toBe(true);
158 expect(body.users[0]).toMatchObject({ username: 'admin', isAdmin: true });
159 });
160});
161
162describe('POST /api/admin/users', () =>
163{
164 test('creates a new user', async () =>
165 {
166 const { status, body } = await req('POST', '/api/admin/users', {
167 username: 'bob', password: 'bobpass1', isAdmin: false, permissions: {},
168 });
169 expect(status).toBe(201);
170 expect(body.ok).toBe(true);
171 });
172
173 test('rejects duplicate username', async () =>
174 {
175 const { status } = await req('POST', '/api/admin/users', {
176 username: 'bob', password: 'bobpass2', isAdmin: false, permissions: {},
177 });
178 expect(status).toBe(409);
179 });
180
181 test('rejects duplicate username with different case', async () =>
182 {
183 const { status } = await req('POST', '/api/admin/users', {
184 username: 'BoB', password: 'bobpass3', isAdmin: false, permissions: {},
185 });
186 expect(status).toBe(409);
187 });
188
189 test('rejects short password', async () =>
190 {
191 const { status } = await req('POST', '/api/admin/users', {
192 username: 'carol', password: 'short', isAdmin: false, permissions: {},
193 });
194 expect(status).toBe(400);
195 });
196
197 test('normalizes permissions so write implies read on create', async () =>
198 {
199 const { status } = await req('POST', '/api/admin/users', {
200 username: 'dora',
201 password: 'dora-pass1',
202 isAdmin: false,
203 permissions: { data: { read: false, write: true } },
204 });
205 expect(status).toBe(201);
206
207 const { body } = await req('GET', '/api/admin/users');
208 const dora = body.users.find(u => u.username === 'dora');
209 expect(dora.permissions).toMatchObject({ data: { read: true, write: true } });
210 });
211});
212
213describe('PATCH /api/admin/users/:id', () =>
214{
215 let bobId;
216
217 beforeAll(async () =>
218 {
219 const { body } = await req('GET', '/api/admin/users');
220 bobId = body.users.find(u => u.username === 'bob').id;
221 });
222
223 test('updates permissions', async () =>
224 {
225 const { status, body } = await req('PATCH', `/api/admin/users/${bobId}`, {
226 permissions: { data: { read: true, write: false } },
227 });
228 expect(status).toBe(200);
229 expect(body.ok).toBe(true);
230 });
231
232 test('returns 404 for unknown user', async () =>
233 {
234 const { status } = await req('PATCH', '/api/admin/users/99999', { isAdmin: false });
235 expect(status).toBe(404);
236 });
237
238 test('normalizes permissions so write implies read on update', async () =>
239 {
240 const { status } = await req('PATCH', `/api/admin/users/${bobId}`, {
241 permissions: { data: { read: false, write: true } },
242 });
243 expect(status).toBe(200);
244
245 const { body } = await req('GET', '/api/admin/users');
246 const bob = body.users.find(u => u.id === bobId);
247 expect(bob.permissions).toMatchObject({ data: { read: true, write: true } });
248 });
249});
250
251describe('DELETE /api/admin/users/:id', () =>
252{
253 let bobId;
254
255 beforeAll(async () =>
256 {
257 const { body } = await req('GET', '/api/admin/users');
258 bobId = body.users.find(u => u.username === 'bob').id;
259 });
260
261 test('cannot delete own account', async () =>
262 {
263 // mock user id is 1 (admin); bob is a different id — but we test self-delete guard
264 const adminId = mockUser.id;
265 const { status } = await req('DELETE', `/api/admin/users/${adminId}`);
266 expect(status).toBe(400);
267 });
268
269 test('deletes another user', async () =>
270 {
271 const { status, body } = await req('DELETE', `/api/admin/users/${bobId}`);
272 expect(status).toBe(200);
273 expect(body.ok).toBe(true);
274 });
275
276 test('cannot delete the last admin', async () =>
277 {
278 // Only 'admin' left; try to delete them (switch mockUser to be different)
279 const { body: users } = await req('GET', '/api/admin/users');
280 const adminUser = users.users.find(u => u.username === 'admin');
281 const { status } = await req('DELETE', `/api/admin/users/${adminUser.id}`);
282 // Our mockUser.id === 1 === adminUser.id, so it should fail with "cannot delete own account"
283 expect([400]).toContain(status);
284 });
285});
286
287describe('GET /api/admin/config', () =>
288{
289 test('returns port and paths', async () =>
290 {
291 const { status, body } = await req('GET', '/api/admin/config');
292 expect(status).toBe(200);
293 expect(body.port).toBe(3000);
294 expect(Array.isArray(body.paths)).toBe(true);
295 });
296});
297
298describe('PUT /api/admin/config', () =>
299{
300 test('saves new paths', async () =>
301 {
302 const { status, body } = await req('PUT', '/api/admin/config', {
303 paths: ['/mnt/newpath'],
304 });
305 expect(status).toBe(200);
306 expect(body.ok).toBe(true);
307 });
308
309 test('rejects non-array paths', async () =>
310 {
311 const { status } = await req('PUT', '/api/admin/config', { paths: 'notanarray' });
312 expect(status).toBe(400);
313 });
314
315 test('rejects invalid port', async () =>
316 {
317 const { status } = await req('PUT', '/api/admin/config', { paths: [], port: 99999 });
318 expect(status).toBe(400);
319 });
320});
321
322describe('POST /api/admin/shutdown', () =>
323{
324 test('responds ok and invokes shutdown callback', async () =>
325 {
326 shutdownForRestartMock.mockClear();
327 const { status, body } = await req('POST', '/api/admin/shutdown');
328 expect(status).toBe(200);
329 expect(body.ok).toBe(true);
330
331 // Shutdown invocation is deferred via setImmediate().
332 await new Promise(resolve => setImmediate(resolve));
333 expect(shutdownForRestartMock).toHaveBeenCalledTimes(1);
334 });
335});
336
337describe('GET /api/admin/update-status', () =>
338{
339 const origInvocationId = process.env.INVOCATION_ID;
340
341 afterEach(() =>
342 {
343 mockExecFileImpl = null;
344 if (origInvocationId === undefined)
345 delete process.env.INVOCATION_ID;
346 else
347 process.env.INVOCATION_ID = origInvocationId;
348 });
349
350 test('returns underSystemd=false when INVOCATION_ID is not set', async () =>
351 {
352 delete process.env.INVOCATION_ID;
353 const { status, body } = await req('GET', '/api/admin/update-status');
354 expect(status).toBe(200);
355 expect(body.underSystemd).toBe(false);
356 expect(body.commitsAhead).toEqual([]);
357 });
358
359 test('returns underSystemd=true and commitsAhead when INVOCATION_ID is set and git reports commits', async () =>
360 {
361 process.env.INVOCATION_ID = 'test-invocation-id';
362 // git fetch succeeds, then git log returns two commits.
363 let callCount = 0;
364 mockExecFileImpl = (_cmd, _args, _opts, cb) =>
365 {
366 callCount++;
367 if (callCount === 1) cb(null, { stdout: '', stderr: '' }); // git fetch
368 else cb(null, { stdout: 'abc1234 Fix bug\ndef5678 Add feature\n', stderr: '' }); // git log
369 };
370 const { status, body } = await req('GET', '/api/admin/update-status');
371 expect(status).toBe(200);
372 expect(body.underSystemd).toBe(true);
373 expect(body.commitsAhead).toEqual(['abc1234 Fix bug', 'def5678 Add feature']);
374 });
375
376 test('returns underSystemd=true and empty commitsAhead when git is up to date', async () =>
377 {
378 process.env.INVOCATION_ID = 'test-invocation-id';
379 let callCount = 0;
380 mockExecFileImpl = (_cmd, _args, _opts, cb) =>
381 {
382 callCount++;
383 cb(null, { stdout: '', stderr: '' }); // fetch and log both return empty
384 };
385 const { status, body } = await req('GET', '/api/admin/update-status');
386 expect(status).toBe(200);
387 expect(body.underSystemd).toBe(true);
388 expect(body.commitsAhead).toEqual([]);
389 });
390
391 test('returns underSystemd=true and empty commitsAhead when git fails', async () =>
392 {
393 process.env.INVOCATION_ID = 'test-invocation-id';
394 mockExecFileImpl = (_cmd, _args, _opts, cb) =>
395 {
396 cb(new Error('git: not found'));
397 };
398 const { status, body } = await req('GET', '/api/admin/update-status');
399 expect(status).toBe(200);
400 expect(body.underSystemd).toBe(true);
401 expect(body.commitsAhead).toEqual([]);
402 });
403});