BlueGit

timfa filemanager

Files

filemanager / tests / admin.routes.test.js

admin.routes.test.js

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